【发布时间】:2017-02-18 02:30:15
【问题描述】:
我尝试写一个多线程程序,遇到了一些问题。
在我运行main.c 之后,我得到了
我:0
新线程 0
新线程 1
我:1
我:1
//main.c
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
void* routine(void* arg)
{
int id = (intptr_t) arg;
printf("new thread %d\n", id);
pthread_exit((void*)(intptr_t) id);
}
int main()
{
pthread_t t[2];
int i;
for(i=0; i<2; i++)
{
int ret = pthread_create (&t[i], NULL, &routine, (void *)(intptr_t) i);
if(ret != 0) {
printf("Error: pthread_create() failed\n");
return -1;
}
}
int id;
/////////here
for(i=0; i<2; i++)
{
printf("i: %d\n",i);
pthread_join(t[i], (void **)&id);
}
/////////here
pthread_exit(NULL);
}
我的问题是
- 为什么最后一个循环运行三次?
- 如果我将
pthread_t t[2]更改为pthread_t t并创建两次,是否可以调用两次pthread_join?
感谢您抽出宝贵时间阅读我的问题。
【问题讨论】:
-
对于第二个问题:否。第二次调用
pthread_create将覆盖pthread_t变量。 -
@JoachimPileborg 我明白了!谢谢@GillBates 我的编译器版本是
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4,运行不正确。有问题吗? -
“运行不正确。”它几乎从不编译器中的错误。
-
@GillBates:运气不好,看起来好像有效。
标签: c multithreading pthreads pthread-join