[英]argument passed to function in pthread_create
我正在尝试使用pthreads和以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* print_thread_num(void *index);
int main(int argc, char** argv) {
int i;
pthread_t threads[3];
for (i = 0; i < 3; i++) {
void *index = &i;
printf("Creating thread %d\n", i);
pthread_create(&threads[i], NULL, print_thread_num, index);
}
pthread_exit(NULL);
}
void* print_thread_num(void *index) {
int i = *(int*)index;
printf("I am the thread at index %d\n", i);
pthread_exit(NULL);
}
我得到以下输出:
Creating thread 0
Creating thread 1
I am the thread at index 1
Creating thread 2
I am the thread at index 2
I am the thread at index 3
为什么每个“我是索引的主题”打印的索引高于应该打印的索引?
您正在传递循环变量i的地址,当您的子线程访问它时,它会在主线程中递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.