我正在尝试找到一种简单的方法来睡眠或停止执行,并唤醒 C 中的另一个(而不是调用的)线程。 它应该像这样工作:
int main(void)
{
int msg = 0;
ptread_t t;
pthread_create(&t, NULL, work, NULL)
while(1)
{
msg = receive_msg();
switch(msg)
case 1:
//sleep_pthread(t);
break;
case 2:
//wake_pthread(t);
break;
default:
break;
}
}
void work(void)
{ //do whatever it needs to
}
receive_msg() 等待用户操作,因此我不知道需要多少时间来停止线程执行。 我需要帮助的是我应该对这些 sleep_pthread(t); 和 wake_pthread(t); 部分使用哪些函数。
从你所说的“找到一种简单的方法来睡眠或停止执行,并唤醒另一个(而不是调用的)C 线程” - 你的要求似乎表明你需要简单的 pthread_cond_wait 或 pthread_cond_timedwait 来满足你的需求。通过使用它们,您将强制它们进入睡眠状态,直到条件不满足或计时器到期。
以下是示例代码
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WAIT_TIME_SECONDS 15
typedef struct mystruct_tag
{
pthread_mutex_t mutex;
pthread_cond_t cond;
int value;
} mystruct_t;
mystruct_t data = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};
/*
* thread start routine. It will set the main thread's predicate and
* signal the condition variable
*/
void *wait_thread (void *arg)
{
int status;
long sleep_time = (long)arg;
status = pthread_mutex_lock(&data.mutex);
if (status != 0)
{
printf(" failed \n");
}
sleep(sleep_time);
data.value = 1; /*set predicate */
status = pthread_cond_signal (&data.cond);
if (status != 0)
{
printf(" failed at condition \n");
}
status = pthread_mutex_unlock (&data.mutex);
return NULL;
}
int main (void)
{
int status;
pthread_t wait_thread_id;
struct timespec timeout;
struct timeval tp;
pthread_create(&wait_thread_id, NULL, wait_thread, (void *)50);
timeout.tv_sec = tp.tv_sec;
timeout.tv_nsec = 0;
timeout.tv_sec += WAIT_TIME_SECONDS;
pthread_mutex_lock(&data.mutex);
while(data.value == 0)
{
pthread_cond_timedwait (&data.cond, &data.mutex, &timeout); /*can use cond_wait too instead of timedwait*/
}
status = pthread_mutex_unlock(&data.mutex);
return 0;
}
您无法从外部休眠或唤醒线程。此外,任何需要此功能的设计都会被破坏。为什么需要将线程置于睡眠状态?您需要的是线程之间的适当同步点,以便线程在没有工作要做时只会等待。