首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无阻塞螺纹

无阻塞螺纹
EN

Stack Overflow用户
提问于 2016-08-16 15:16:52
回答 1查看 315关注 0票数 1

我读过在堆栈溢出上的帖子,但没有人告诉我我想做什么。

在我的例子中,我希望创建一个线程,启动它,让它在没有阻塞状态下运行,只要主进程运行。这个线程没有通信,没有同步与主进程,它做自己的工作完全独立。

请考虑以下代码:

代码语言:javascript
运行
复制
 #define DAY_PERIOD 86400 /* 3600*24 seconds */
 int main() {
   char wDir[255] = "/path/to/log/files";
   compress_logfiles(wDir);

   // do other things, this things let the main process runs all the time.
   // just segmentation fault, stackoverflow, memory overwrite or 
   // somethings like that stop it.

   return 0;
}

/* Create and launch thread */
void compress_logfiles(char *wDir)
{

    pthread_t compressfiles_th;

    if (pthread_create(&compressfiles_th, NULL, compress, wDir)) 
    {
        fprintf(stderr, "Error create compressfiles thread\n");
        return;
    }
    if (pthread_join(compressfiles_th, NULL)) 
    {
        //fprintf(stderr, "Error joining thread\n");
        return;
    }
   return;
}

void *compress(void *wDir)
{
    while(1)
    {
        // Do job to compress files
        // and sleep for one day 
        sleep(DAY_PERIOD); /* sleep one day*/
    }
    return NULL;
}

使用compress_logfiles函数中的ptheard_join,线程成功地压缩所有文件,并且不会返回,因为它在无限中,而循环,因此主进程仍然一直被阻塞。如果我从compress_logfiles函数中删除ptheard_join,则主进程不会被阻塞,因为它不会等待线程返回,但是线程会压缩一个文件并退出(有很多文件,其中有一个文件)。

那么,是否有办法让主进程启动compressfiles_th线程,让它在不等待完成或退出的情况下完成自己的工作?我在pthread_tryjoin_nppthread_timedjoin_np中找到了Linux程序员手册,似乎pthread_tryjoin_np做的工作如果我不关心返回的值,那么使用它是个好主意?

谢谢。

编辑1:

请注意,主进程在调用compress_logfiles(wDir)后是去功能化的,也许去功能化扼杀了主进程并重新启动,这是问题所在吗?

编辑2:解决方案

dbush的信贷

是的,叉子导致了这个问题,而pthread_atfork()解决了它。我做了这个更改来运行compressfiles_th,而不阻塞主进程:

代码语言:javascript
运行
复制
 #define DAY_PERIOD 86400 /* 3600*24 seconds */
 char wDir[255] = "/path/to/log/files"; // global now

 // function added
void child_handler(){
    compress_logfiles(wDir); // wDir is global variable now
}

 int main() 
 {
     pthread_atfork(NULL, NULL, child_handler);
     // Daemonize the process.
     becomeDaemon(BD_NO_CHDIR & BD_NO_CLOSE_FILES & BD_NO_REOPEN_STD_FDS & BD_NO_UMASK0 & BD_MAX_CLOSE);
   // do other things, this things let the main process runs all the time.
   // just segmentation fault, stackoverflow, memory overwrite or 
   // somethings like that stop it.

   return 0;
}

child_handler()函数在叉后调用.叉子

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-16 15:29:34

当您fork一个新进程时,只有调用线程被复制,而不是所有线程

如果您想要去守护,您需要首先创建fork,然后创建线程。

来自叉子手册页

子进程是用单个线程创建的--这个线程称为()。父节点的整个虚拟地址空间将复制到子节点中,包括互斥变量、条件变量和其他线程对象的状态;使用pthread_atfork(3)可能有助于处理由此可能造成的问题。

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

https://stackoverflow.com/questions/38978606

复制
相关文章

相似问题

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