64,648
社区成员
发帖
与我相关
我的任务
分享
using namespace std;
pthread_mutex_t mutex;
pthread_cond_t cond;
bool stoped = false;
void *fun(void* data);
int main() {
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond, NULL);
pthread_t thread;
pthread_create(&thread, 0, fun, 0);
int cmd;
while(std::cin >> cmd)
{
switch(cmd)
{
case 1:
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
break;
}
case 99:
{
stoped = true;
break;
}
}
}
void *ret;
pthread_join(thread, &ret);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
void *fun(void* data)
{
pthread_mutex_lock(&mutex);
printf("%d\n", pthread_cond_signal(&cond));
pthread_mutex_unlock(&mutex);
while(!stoped)
{
struct timespec outtime;
struct timeval now;
pthread_mutex_lock(&mutex);
//超时等待50毫秒
uint ms = 50;
gettimeofday(&now, NULL);
now.tv_usec += ms * 1000;
if(now.tv_usec >= 1000000)
{
now.tv_sec += now.tv_usec / 1000000;
now.tv_usec %= 1000000;
}
outtime.tv_nsec = now.tv_usec;
outtime.tv_sec = now.tv_sec;
int ret = pthread_cond_timedwait(&cond, &mutex, &outtime);
pthread_mutex_unlock(&mutex);
if (ret == 0)
{
printf("ok\n");
}
else
{
//printf("timeout \n");
}
//每次循环不管是其他线程主动有数据还是等待超时,这里都做点什么
int n ;
for (int i=0;i<100;i++)
{
if (i % 3 == 0)
{
n++;
}
}
}
return 0;
}