首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尽管从pthread_create()返回成功,但未创建任何线程

问尽管从pthread_create()返回成功,但未创建任何线程
EN

Stack Overflow用户
提问于 2020-10-16 02:08:01
回答 1查看 28关注 0票数 2

我已经在HP-UX甚至SUSE上写了相当多的线程代码,而且运行得很好。但它在红帽上不起作用。这是我的机器:

Linux版本3.10.0-1062.18.1.el7.x86_64 (Red Hat 4.8.5-39)

Red_Hat_Enterprise_Linux-Release_Notes-7-en-US-7-2.el7.noarch

redhat-版本-服务器-7.7-10.el7.x86_64

我写了一个简单的测试程序thr_ex.c:

代码语言:javascript
复制
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>



void *funny(void *);



void *funny(s)
void *s;

{ 
    int fd;


    fd = creat("/tmp/funny_func", 0600);

    write(fd, s, strlen((char *) s));

    close(fd);
}



int main()

{
    int                 return_value;
    pthread_t           thread_id;
    pthread_attr_t      thread_attr;


    pthread_attr_init(&thread_attr);
    pthread_attr_setscope(&thread_attr, PTHREAD_SCOPE_SYSTEM);
    pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

    return_value = pthread_create(&thread_id, &thread_attr, funny, (void *) "Here I am\n");

    printf("Return value == %d\n", return_value);
    printf("Thread id    == %hu\n", thread_id);

    exit(0);
} /* End main. */

编译,构建:

gcc -pthread -s -o thr_ex thr_ex.c

运行:

./thr_ex

返回值== %0

线程id == 5888

但是在/tmp下不会创建任何文件。strace -f没有显示creat()或write() (除了main ()中的printf )。

但是,strace -f确实会显示,例如:忽略未知pid 64574的strace: Exit

我尝试过更简单的代码,其中线程只运行printf()和fflush(),没有线程属性,也没有函数的参数。还是什么都没发生。

EN

回答 1

Stack Overflow用户

发布于 2020-10-16 02:22:33

在main中的return语句或exit( 0)语句之前插入

代码语言:javascript
复制
pthread_exit( NULL );

否则,创建的线程可能没有时间执行,因为进程将结束。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64377404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档