C pthread不起作用

c++ pthread not working

本文关键字:不起作用 pthread      更新时间:2023-10-16

我有一个创建线程的classa,我希望线程运行直到将变量设置为false。

我创建类似的线程:

ClassA::ClassA():
m_bContinue(true),
{
    pthread_mutex_init(&m_mutex, NULL);
    pthread_create(&m_thWorkThread, NULL, &ClassA::ThreadProc, this);
}

我想要线程运行长,只要pclassa->继续()返回true。

void* ClassA::ThreadProc(void *p) //ThreadProc defined as static member function
{
    ClassA *pClassA = reinterpret_cast<ClassA*>(p);
    if(pClassA != NULL)
    {
        while(pClassA->Continue())
        {
            printf("in the while n ");
        }
    }
    else
        printf("pClassA null n");
}

继续返回M_BContinue,该M_BContinue设置为构造器中的true。

bool ClassA::Continue()
{
   return bContinue;
}

当我运行它时,它只会在循环一次时进入并打印" while"并停止程序。当我进行街头时,我看到了Sigsegv 杀死的消息 。当我更改时循环时:

while(1){}

它正常工作。我想念什么?

您不能使用pthread_create启动成员功能。而是使用正常功能,将this传递给它,然后调用所需的功能:

void *ThreadProc (void *p)
{
  reinterpret_cast<ClassA*>(p)->ThreadProc (p);
  return 0;
}
...
pthread_create(&m_thWorkThread, NULL, &ThreadProc, this);

或,您可以使用允许启动类成员功能的C 11及其std::thread

类型A的对象的寿命比线程短?似乎对象死亡太早了。使用while(1),您不再引用A。

快速问题。pthread_join在哪里。希望您还没有错过它。只是好奇。