C新手,我正在閱讀here關於如何正確地將參數傳遞給線程。如果這個參數需要傳遞給多個線程呢?我在哪裏/如何使用free()
?你說:將參數傳遞給多個線程
void *foo(void *i) {
int a = *((int *) i);
while(1){
printf("foo running \n");
sleep(1);
}
}
void *bar(void *i) {
int a = *((int *) i);
while(1){
printf("bar running \n");
sleep(1);
}
}
int main() {
pthread_t threads[2];
int i;
for (i = 0; i < 2; i++) {
int *arg = malloc(sizeof(*arg));
if (arg == NULL) {
fprintf(stderr, "Couldn't allocate memory for thread arg.\n");
exit(1);
}
*arg = i;
pthread_create(&threads[0], NULL, foo, arg);
pthread_create(&threads[1], NULL, bar, arg);
}
for (i = 0; i < 2; i++){
pthread_join(threads[i],NULL);
}
return 0;
}
正在孕育線程同樣的事情後,調用main
free(arg);
/安全嗎?
順便說一句。你想在'for()'循環中調用2'pthread_create()'嗎? – chux