在等待条件变量时有一个睡眠的pthread。我在外部while循环中使用布尔值来保持它运行。我似乎遇到的问题是,当我更改此变量时,线程不会死亡。
我看了一下乐器,如果我开始一个线程,告诉它死了,然后开始一个新线程我的线程数是2而不是1.
如何在我想要的时候正确销毁这个帖子?
int worktodo=0;
BOOL runthread=NO;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void *threadfunc(void *parm)
{
int rc;
while(runthread==YES)
{
rc=pthread_mutex_lock(&mutex);
while(!worktodo)
{
printf("thtread blocked\n");
rc=pthread_cond_wait(&cond, &mutex);
}
printf("thtread awake.... doing work\n");
// doing work
worktodo=0;
rc=pthread_mutex_unlock(&mutex);
}
// never reaches here!!
pthread_detach(NULL);
}
void makeThread()
{
pthread_attr_t attr;
int returnVal;
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
runthread=YES;
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
int threadError = pthread_create(&str->thread, &attr, &threadfunc, NULL);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
// Report an error.
}
}
void wakethread()
{
pthread_mutex_lock(&mutex);
worktodo=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
void killthread
{
runthread=NO;
}
答案 0 :(得分:1)
void killthread
{
runthread=NO;
pthread_mutex_lock(&mutex);
worktodo=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
答案 1 :(得分:0)
将runthread初始化为NO并将其与YES进行比较。线程永远不会到达其内部
while(runthread==YES)
环。此外,当线程等待工作时,killthread不会将其唤醒,并且runthread将保持其工作等待循环。