pthread的 - 如何开始运行一个新的线程,而不调用加入? [英] pthread - How to start running a new thread without calling join?

查看:106
本文介绍了pthread的 - 如何开始运行一个新的线程,而不调用加入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从主线程启动一个新线程。我不能用加入,因为我不想等待线程退出,比恢复执行。结果
基本上,我需要的是像pthread_start(...),但无法找到它。

编辑:结果
由于所有建议create_thread的答案应该开始线程的问题是,在简单的code下面这是行不通的。下面的程序的输出是主线程。好像从来没有执行的子线程。任何想法,我错了?结果
编译在Fedora 14版本的GCC 4.5.1运行

 无效* thread_proc(无效* X)
{
   的printf(子线程\\ n);
   了pthread_exit(NULL);
}
诠释的main()
{
    T1的pthread_t;
    INT解析度=在pthread_create(安培; T1,NULL,thread_proc,NULL);
    如果(RES)
    {
        的printf(错误%d个\\ N,RES);
    }    的printf(主线程\\ n);
    返回0;
}


解决方案

要启动线程的功能是在pthread_create ,不
在pthread_join 。你只用在pthread_join 当你准备好等待,
并重新同步,如果你脱离线程,有没有必要使用
它。您也可以从不同的线程加入。

在退出之前(通过调用退出或从 main返回),
你必须确保没有其他线程运行。单程(但不
唯一的),要做到这一点是与所有你已经线程加盟
创建。

I want to start a new thread from the main thread. I can't use join since I don't want to wait for the thread to exit and than resume execution.
Basically what I need is something like pthread_start(...), can't find it though.

Edit:
As all of the answers suggested create_thread should start thread the problem is that in the simple code below it doesn't work. The output of the program below is "main thread". It seems like the sub thread never executed. Any idea where I'm wrong?
compiled and run on Fedora 14 GCC version 4.5.1

void *thread_proc(void* x)
{
   printf ("sub thread.\n");
   pthread_exit(NULL);
}


int main()
{
    pthread_t t1;
    int res = pthread_create(&t1, NULL, thread_proc, NULL);
    if (res)
    {
        printf ("error %d\n", res);
    }

    printf("main thread\n");
    return 0;
}

解决方案

The function to start the thread is pthread_create, not pthread_join. You only use pthread_join when you are ready to wait, and resynchronize, and if you detach the thread, there's no need to use it at all. You can also join from a different thread.

Before exiting (either by calling exit or by returning from main), you have to ensure that no other thread is running. One way (but not the only) to do this is by joining with all of the threads you've created.

这篇关于pthread的 - 如何开始运行一个新的线程,而不调用加入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆