我的程序所需的功能:
使用命令行用户输入N和M。 N是将要创建的新线程的数量,并且M是每个线程增加全局变量的数量A。为什么使用线程时我的程序输出总是不一样?
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
static int A = 0;
void *Thread(void* x){
int i;
int n = *((int*)x);
for (i = 0; i<n; i++){
A++;
}
}
int main(int argc, char* argv[]){
int i;
int N = atoi(argv[1]);
int M = atoi(argv[2]);
pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t)*N);
if(!thread){
printf("No memory\n");
exit(2);
}
for (i = 0; i< N; i++){
if (pthread_create(&thread[i], NULL, Thread, &M)){
printf("Not able to create a thread\n");
exit(1);
}
}
for(i = 0; i< N; i++)
pthread_join(thread[i], NULL);
printf("A = %d\n", A);
return 0;
}
的问题是,我每次运行它的时候有不同的输出。 Screenshot of my terminal when i run the program multiple times in a row
应当保护并发读/写访问变量(此处为'A')。例如通过使用互斥锁。 – alk
OT:这个强制转换'(pthread_t *)'在C中没用。或者你应该使用C++编译器吗? – alk
关于使用互斥锁:http://stackoverflow.com/q/34524/694576 – alk