【问题标题】:No thread created despite success on return from pthread_create()尽管从 pthread_create() 返回成功,但没有创建线程
【发布时间】:2021-01-30 06:46:08
【问题描述】:

我已经在 HP-UX 甚至 SUSE 上编写了很多线程代码,并且运行良好。但它不适用于红帽。这是我的机器:

Linux 版本 3.10.0-1062.18.1.el7.x86_64(红帽 4.8.5-39)

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

redhat-release-server-7.7-10.el7.x86_64

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

#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 确实显示,例如: strace: 未知 pid 64574 的退出被忽略

我尝试过更简单的代码,其中线程只运行 printf() 和 fflush(),没有线程属性,也没有函数参数。仍然没有任何反应。

【问题讨论】:

  • 你在哪里找到这个例子,带有古老的 K&R 函数参数定义?
  • 至于你的问题,你永远不会等待线程完成。相反,您在创建线程后立即终止进程(这意味着它甚至可能没有时间运行)。
  • @Anders 插入 pthread_exit( NULL );在返回之前。
  • 详细来说,当进程结束时(exit(0))进程的所有线程都以它结束。要让分离的线程(以及进程本身)在“后台”运行,只需退出“主线程”(使用pthread_exit 而不是exit)。
  • 或者,让第二个线程可加入,并在exit()ing 程序之前加入它。

标签: c linux pthreads posix


【解决方案1】:

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

pthread_exit( NULL );

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

【讨论】:

  • 换句话说,程序在第二个线程执行的所有内容和主线程执行的exit(0)之间存在竞争条件。
  • @JohnBollinger 没错,谢谢。我只是认为第二个线程至少有时间执行我运行的所有测试的几次。
猜你喜欢
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多