我正在学习如何在C中使用线程,我想做一个可以同时做两件事的程序,我想这就是并行性的定义。所以我用下面的代码创建线程:
pthread_t threads[NUM_THREADS];
int rc, rc_2;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
printf("main() : creating thread, %d\n", i);
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
rc_2 = pthread_create(&threads[i], NULL, PrintHello_2, (void *)i);
if (rc || rc_2) {
printf("Error:unable to create thread, %d\n", rc);
exit(-1);
}
}这些线程中的每一个都会调用以下函数之一:
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
printf("Hello World! Thread ID, %d\n", tid);
printf("Valores a: %d, b: %d\n", a,b);
a += 5;
pthread_exit(NULL);
}
void *PrintHello_2(void *threadid) {
long tid;
tid = (long)threadid;
printf("Hello World! Thread ID, %d\n", tid);
printf("Valores a: %d, b: %d\n", a,b);
b += 3;
pthread_exit(NULL);
}我有两个全局变量a,b,我只是将它们相加5和3,以显示它们是如何变化的。但问题是,我不明白这是不是parallelism..if,而不是我怎么能看到这两个函数或操作同时执行它们的代码?因为当我打印a和b值时,它看起来像是一个普通的程序。
发布于 2021-09-27 02:08:46
在线程有机会运行任意时间长度之前,main()就会退出。pthread_join()将在main()中等待线程退出。另一个问题是你的线程并不是特别长时间运行。我通过运行一个长循环修复了这个问题。还修复了将int传递给线程但读取长的问题。
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 2
void *PrintHello(void *threadid) {
int tid = *(int *) threadid;
for(int i = 0; i < INT_MAX; i += tid + 1) {
printf("%d %d\n", tid, i);
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int ids[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++ ) {
ids[i] = i;
printf("main() : creating thread, %d\n", i);
int rc = pthread_create(&threads[i], NULL, PrintHello, &ids[i]);
if (rc) {
printf("Error:unable to create thread, %d\n", rc);
exit(-1);
}
}
for(int i = 0; i < NUM_THREADS; i++ ) {
pthread_join(threads[i], 0);
}
}这会打印出类似这样的内容:
1 166
0 265
0 266
1 168
0 267
1 170
1 172
1 174
1 176
1 178
0 268输出流必须有一个互斥锁,否则两个线程会产生混杂的输出。
https://stackoverflow.com/questions/69340213
复制相似问题