Tag: pthread join

pthread:加入一个分离的线程没有正确设置errno

我正在检查’pthread_join’的行为并拥有以下代码: #include #include #include #include #include void *thread(void *vargp) { pthread_detach(pthread_self()); pthread_exit((void *)42); } int main() { int i = 1; pthread_t tid; pthread_create(&tid, NULL, thread, NULL); sleep(1); pthread_join(tid, (void **)&i); printf(“%d\n”, i); printf(“%d\n”, errno); } 在我的平台上观察到的输出(Linux 3.2.0-32-generic#51-Ubuntu SMP x86_64 GNU / Linux): 用’sleep(1)’注释掉:42 0 使用sleep语句,它产生:1 0 根据pthread_join的手册页,当我们尝试加入一个不可连接的线程时,我们应该得到错误’ EINVAL ‘,但是,上面两种情况都没有设置errno。 而且在第一种情况下,似乎我们甚至可以获得分离线程的退出状态,我对结果感到困惑。 谁能解释一下呢? 谢谢 [编辑]:我意识到第一个printf可能会重置’errno’,但是,即使我交换了两个’printf’语句的顺序后,我仍然得到了相同的结果。

pthread_join()用于异步线程

我编写了一个简单的演示程序,以便我可以理解pthread_join()函数。 我知道如何使用pthread_condition_wait()函数来允许异步线程,但我正在尝试理解如何使用pthread_join()函数执行类似的工作。 在下面的程序中,我将Thread 1s ID传递给Thread 2s函数。 在Thread 2s函数中,我调用pthread_join()函数并传入Thread 1s ID。 我希望这会导致线程1首先运行,然后线程2运行第二,但我得到的是它们都同时运行。 这是因为一次只有一个线程可以使用pthread_join()函数,并且当我从主线程调用它时我已经在使用pthread_join()函数了吗? #include #include #include void *functionCount1(); void *functionCount2(void*); int main() { /* How to Compile gcc -c foo gcc -pthread -o foo foo.o */ printf(“\n\n”); int rc; pthread_t thread1, thread2; /* Create two thread –I took out error checking for clarity*/ pthread_create( &thread1, NULL, […]

对pthread_create()中的参数感到困惑

我的问题:为什么不直接传递&i作为pthread_create()的最后一个参数? 相反,他创建一个数组来保持相同的东西…. #define THREAD_CT 2 /* bump this up a few numbers if you like */ void *print_stuff(void *ptr) { int i, id= * (int *) ptr; for (i= 0; i < 5; i++) { printf("Thread %d, loop %d.\n", id, i); sleep(rand() % 2); /* sleep 0 or 1 seconds */ } printf("Thread %d exiting.\n", […]