gpt4 book ai didi

c++ - 以安全的方式了解 pthread 线程是否处于事件状态

转载 作者:行者123 更新时间:2023-11-28 08:23:21 26 4
gpt4 key购买 nike

我制作了一个连续生成/销毁 100 个线程的多线程应用程序:

//Here is the thread class (one by every thread
struct s_control
{
data_in[D_BUFFER_SIZE];//data in to thread
data_out[D_BUFFER_SIZE];//data generated by the thread
//I use volatile in order to status data is avaiable in and out of the thread:
volatile __int16 status;//thread state 0=empty,1=full,2=filling (thread running)
}*control;

//Here is the thread main function
static void* F_pull(void* vv)//=pull_one_curl()
{
s_control* cc = (s_control* ) vv;
//use of cc->data_in and filling of cc->data out
cc->status=1; //Here advises that thread is finished and data out is filled
return NULL;
}

void main()
{
initialization();
control=new s_control[D_TAREAS];
pthread_t *tid=new pthread_t[D_TAREAS];
for (th=0;th<D_TAREAS;th++)
{ //Access to status of thread at the beginning
//(to avoid if it changes in the middle):
long status1=control[th].status
if (status1==0) //Thread finished and data_out of thread is empty
{ control[i2].status=2; //Filling in (thread initiated)status LLENANDO
error = pthread_create(&tid[th],NULL,F_pull,(void *) &control[th]);
}
else if (status1==1) //Thread finished and data_out of thread is full
{
//do things with control[th].data_out;
//and fill in control[th].data_in with data to pass to next thread
control[th].status=0; //Thread is finished and now its data_out is empty
}
else
{
//printf("\nThread#%li:filling",i2);
}
}while(!_kbhit());
finish();
}

然后如您所见,在线程结束时,我使用变量 volatile 来通知线程即将退出:

begin of thread{ ....
cc->status=1; //Here advises that thread is finished and data out is filled
return NULL;
}//END OF THREAD

但是在cc->status设置为1之后,线程还没有结束(多了一行)

所以我不喜欢在线程内设置状态。我尝试了 pthread_kill,但它没有用,因为它在线程处于事件状态之前不起作用,如在以下位置所见: pthread_kill

最佳答案

我不确定这是否回答了您的问题,但是您可以使用 pthread_join() 来等待线程终止。结合一些(适当同步的)状态变量,您应该能够实现您所需要的。

关于c++ - 以安全的方式了解 pthread 线程是否处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4992608/

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