下面这个程序存在竞争,当对等线程执行 int myid = *((int *)argv) 前,如果主线程先执行了 i++,那么对等线程的执行结果是不正确。
- #include <stdio.h>
- #include <pthread.h>
- #define N 100
- void *thread(void *argv)
- {
- int myid = *((int *)argv);
- printf("hello from thread %d\n", myid);
- return NULL;
- }
- int main(int argc, char **argv)
- {
- pthread_t tid[N];
- int i;
- for(i = 0; i < N; i++)
- pthread_create(&tid[i], NULL, thread, &i);
- for(i = 0; i < N; i++)
- pthread_join(tid[i], NULL);
- return 0;
- }
- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
- #define N 100
- void *thread(void *argv)
- {
- int myid = *((int *)argv);
- free(argv); //释放空间
- printf("hello from thread %d\n", myid);
- return NULL;
- }
- int main(int argc, char **argv)
- {
- pthread_t tid[N];
- int i, *p;
- for(i = 0; i < N; i++)
- {
- p = malloc(sizeof(int)); //动态为每一个 id 分配内存
- *p = i;
- pthread_create(&tid[i], NULL, thread, p);
- }
- for(i = 0; i < N; i++)
- pthread_join(tid[i], NULL);
- return 0;
- }
- #include <stdio.h>
- #include <pthread.h>
- #define N 100
- void *thread(void *argv)
- {
- int myid = (int) argv;
- printf("hello from thread %d\n", myid);
- return NULL;
- }
- int main(int argc, char **argv)
- {
- pthread_t tid[N];
- int i;
- for(i = 0; i < N; i++)
- pthread_create(&tid[i], NULL, thread, (void *)i);
- for(i = 0; i < N; i++)
- pthread_join(tid[i], NULL);
- return 0;
- }