【问题标题】:Implementing worker threads (in Linux): How offensive is this?实现工作线程(在 Linux 中):这有多令人反感?
【发布时间】:2009-04-21 18:02:26
【问题描述】:
#include <pthread.h>
static void * worker_thread(void *);

void some_func(void)
{
    pthread_t * tmp;
    tmp = malloc(sizeof(pthread_t));
    if (NULL != tmp)
    {
        if (!pthread_create(tmp, NULL, worker_thread, (void *)tmp))
            pthread_detach(*tmp);
        else
            free(tmp);
    }
}

static void * worker_thread(void * p)
{
    /* do work */
    free(p);
    return(NULL);
}

【问题讨论】:

  • 我觉得你的冒犯很冒犯。
  • 你有一个竞争条件。在实际使用它来分离线程之前,您最终可能会释放 tmp。为什么不直接使用堆栈变量?
  • 当心人们可能会标记它
  • 无论如何,代码看起来很可疑。我不认为这是正确的。虽然我缺乏 pthread 知识
  • @Jamie:内核会管理你的线程。如果你不需要它,你对标识符做什么并不重要(除非你释放它然后使用它:p)。此外,线程可以自行分离。调用 pthread_self() 从新线程中获取线程标识符。你经常看到:pthread_detach(pthread_self());

标签: linux multithreading posix pthreads


【解决方案1】:

我从 cmets 中了解到,pthread_t 结构在线程期间不需要“活动”(这是我的想法以及我使用 malloc 的原因);堆栈变量很好。我最终做的是基于 Jason Coco 的评论:

#include <pthread.h>

static void * worker_thread(void *);

void start_worker(void * arg)
{
    pthread_t tmp;
    (void)pthread_create(& tmp, NULL, worker_thread, arg))
}

static void * worker_thread(void * p)
{
    /* do work */

    /* finished work */
    pthread_detach(pthread_self());
    return (p);
}

【讨论】:

  • 还有一件事 - 忽略 pthread_create 的返回值可能是个坏主意。否则你的程序可能会死锁或做错事......
猜你喜欢
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 2022-01-23
  • 2021-07-23
相关资源
最近更新 更多