关于 pthread_join() 和 pthread_detach() 的问题

AXE47

我编写了这个程序来练习 pthread 系统调用,所以我使用了一些打印行来检查结果,但它们被转义了,输出是:

Thread 1 created Thread 2 created test3

虽然我认为应该是

thread 1 created test2 thread 2 created test3 test1 顺序可能会改变,但我应该有这行,所以为什么要逃避这个打印语句?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>



void *function();
void *function2();




int main(int argc, char *argv[])
{
    pthread_t tid;
    int rc;
    rc = pthread_create(&tid, NULL, function(), NULL);
    if(rc > 0){
        fprintf(stderr, "Error\n");
        exit(1);
    }
    pthread_join(tid, NULL);
    sleep(1);
    printf("test1\n");
    pthread_exit(NULL);
}

void *function(){
    int rc;
    pthread_t tid;
    printf("Thread 1 created\n");
    rc = pthread_create(&tid, NULL, function2(), NULL);
    if(rc > 0){
        fprintf(stderr, "Error\n");
        exit(1);
    }
    printf("test2\n");
    pthread_exit(NULL);
}

void *function2(){
    pthread_detach(pthread_self());
    printf("Thread 2 created\n");
    printf("test3\n");
    pthread_exit(NULL);
}
肖恩
rc = pthread_create(&tid, NULL, function(), NULL);

您正在尝试pthread_create()使用function()作为在新线程中运行的函数调用返回的指针进行调用(请记住,函数参数在调用函数本身之前得到评估)。现在,function()实际上并不返回任何值,但是它呼吁function2()在它的身上(而评估的参数再调用pthread_create()),它不会返回任何值,但不会打电话pthread_exit()来代替。由于此时只有一个线程,因为只有主进程线程在运行(pthread_create()实际上还没有被调用;调用堆栈看起来像main() -> function() -> function2()),整个程序然后退出。

您需要pthread_create()使用指向functionand 的指针进行调用function2不是调用它们的结果:

rc = pthread_create(&tid, NULL, function, NULL);

等等。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

关于线程的pthread_join()和pthread_detach()的“回收存储”是什么意思?

来自分类Dev

pthread_join和pthread_exit

来自分类Dev

关于PThread和PThread屏障

来自分类Dev

不使用pthread_detach或pthread_join,会不会为其他新创建的线程清理资源?

来自分类Dev

即使在pthread_detach之后也会泄漏

来自分类Dev

在示例的x64窗口上,崩溃在pthread_cancel和pthread_join上

来自分类Dev

在Linux中何时使用pthread_exit()和何时使用pthread_join()?

来自分类Dev

在同一循环中集成pthread_create()和pthread_join()

来自分类Dev

如何用clone()替换pthread_join()和pthread_create()

来自分类Dev

pthread_join和pthread_mutex_lock有什么区别?

来自分类Dev

在示例的x64窗口上,崩溃在pthread_cancel和pthread_join上

来自分类Dev

在pthread_join()上查询

来自分类Dev

pthread_join()意外结果

来自分类Dev

pthread_join分段错误

来自分类Dev

在pthread_join()中阻塞

来自分类Dev

pthread_join void ** retval

来自分类Dev

函数pthread_join的代码-Pthread库

来自分类Dev

pthread_detach()在64位Linux上导致SIGSEGV

来自分类Dev

存在现有联接程序时的pthread_detach行为

来自分类Dev

链表和pthread的问题

来自分类Dev

未定义的引用(readline,pthread_create,pthread_detach),makefile不包含库

来自分类Dev

多次调用pthread_join如何工作?

来自分类Dev

pthread_join()无法正常工作

来自分类Dev

pthread_join不影响主线程

来自分类Dev

pthread_join中的段错误

来自分类Dev

pthread_join()用于异步线程

来自分类Dev

pthread_join free():无效的指针错误

来自分类Dev

C中的pthread_join函数

来自分类Dev

pthread_join死锁的简单示例

Related 相关文章

热门标签

归档