gpt4 book ai didi

cout - Simple Detached pthread 不会取消! (即使互斥, cout 也会阻塞和交错)

转载 作者:行者123 更新时间:2023-12-04 06:57:07 25 4
gpt4 key购买 nike

我在这里有一个难题,我无法解决,也没有在网上找到正确的答案:

我创建了一个带有清理路由的分离线程,问题是在我的 Imac 和 Ubuntu 9.1(双核)上。我无法正确取消空闲代码中的分离线程:

#include <iostream>
#include <pthread.h>
#include <sched.h>
#include <signal.h>

#include <time.h>

pthread_mutex_t mutex_t;

using namespace std;

static void cleanup(void *arg){
pthread_mutex_lock(&mutex_t);
cout << " doing clean up"<<endl;
pthread_mutex_unlock(&mutex_t);
}


static void *thread(void *aArgument)
{

pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);

pthread_cleanup_push(&cleanup,NULL);
int n=0;
while(1){
pthread_testcancel();
sched_yield();
n++;

pthread_mutex_lock(&mutex_t);
cout << " Thread 2: "<< n<<endl; // IF I remove this endl; --> IT WORKS!!??
pthread_mutex_unlock(&mutex_t);

}
pthread_cleanup_pop(0);

return NULL;
}


int main()
{

pthread_t thread_id;

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

int error;

if (pthread_mutex_init(&mutex_t,NULL) != 0) return 1;

if (pthread_create(&thread_id, &attr, &(thread) , NULL) != 0) return 1;

pthread_mutex_lock(&mutex_t);
cout << "waiting 1s for thread...\n" <<endl;
pthread_mutex_unlock(&mutex_t);

int n =0;

while(n<1E3){
pthread_testcancel();
sched_yield();
n++;

pthread_mutex_lock(&mutex_t);
cout << " Thread 1: "<< n<<endl;
pthread_mutex_unlock(&mutex_t);
}

pthread_mutex_lock(&mutex_t);
cout << "canceling thread...\n" <<endl;
pthread_mutex_unlock(&mutex_t);

if (pthread_cancel(thread_id) == 0)
{
//This doesn't wait for the thread to exit
pthread_mutex_lock(&mutex_t);
cout << "detaching thread...\n"<<endl;
pthread_mutex_unlock(&mutex_t);

pthread_detach(thread_id);

while (pthread_kill(thread_id,0)==0)
{
sched_yield();
}

pthread_mutex_lock(&mutex_t);
cout << "thread is canceled";
pthread_mutex_unlock(&mutex_t);

}

pthread_mutex_lock(&mutex_t);
cout << "exit"<<endl;
pthread_mutex_unlock(&mutex_t);

return 0;
}

当我用 printf() 替换 Cout 时,我一直工作到最后“退出”,但是使用 cout(甚至锁定),可执行文件在输出“分离线程...

从专业人士那里知道会很酷,这里的问题是什么?。
为什么即使 cout 被互斥锁锁定,这也不起作用!?

最佳答案

问题在于 COUT 有一个隐式取消点!

我们需要这样编码:

pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
pthread_testcancel();
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);

并在开头制作线程:
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);

这确保只有 pthread_cancel() 有取消点......

关于cout - Simple Detached pthread 不会取消! (即使互斥, cout 也会阻塞和交错),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2440576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com