33,311
社区成员
发帖
与我相关
我的任务
分享
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <iostream>
using namespace std;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread_func(void* param);
int main()
{
pthread_mutex_init(&mutex, nullptr);
pthread_cond_init(&cond, nullptr);
pthread_t t_id[5] = { 0 };
for (int i = 0; i < 5; i++)
{
pthread_create(&t_id[i], nullptr, thread_func, nullptr);
}
sleep(7);
pthread_cond_broadcast(&cond);
//pthread_cond_signal(&cond);
for (int i = 0; i < 5; i++)
{
pthread_join(t_id[i], nullptr);
}
return 0;
}
void* thread_func(void* param)
{
pthread_mutex_lock(&mutex);
struct timeval now;
struct timespec outtime;
while (true)
{
gettimeofday(&now, NULL);
outtime.tv_sec = now.tv_sec + 3;
outtime.tv_nsec = now.tv_usec * 1000;
int res = pthread_cond_timedwait(&cond, &mutex, &outtime);
if (res == ETIMEDOUT)
{
cout << "etime out " << pthread_self() << endl;
}
else if (res == 0)
{
cout << "res = 0." << endl;
break;
}
else
{
cout << "res = " << res << endl;
}
sleep(1);
}
cout << "thread: " + to_string(pthread_self()) + " exit." << endl;
pthread_mutex_unlock(&mutex);
return nullptr;
}
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <iostream>
#include <string>
using namespace std;
#define nullptr NULL
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread_func(void* param);
int main()
{
pthread_mutex_init(&mutex, nullptr);
pthread_cond_init(&cond, nullptr);
pthread_t t_id[5] = { 0 };
for (int i = 0; i < 5; i++)
{
pthread_create(&t_id[i], nullptr, thread_func, nullptr);
}
sleep(7);
pthread_cond_broadcast(&cond);
//pthread_cond_signal(&cond);
for (int i = 0; i < 5; i++)
{
pthread_join(t_id[i], nullptr);
}
return 0;
}
void* thread_func(void* param)
{
struct timeval now;
struct timespec outtime;
pthread_t pid = pthread_self();
while (true)
{
gettimeofday(&now, NULL);
outtime.tv_sec = now.tv_sec + 3;
outtime.tv_nsec = now.tv_usec * 1000;
pthread_mutex_lock(&mutex);
int res = pthread_cond_timedwait(&cond, &mutex, &outtime);
if (res == ETIMEDOUT)
{
pthread_mutex_unlock(&mutex);
cout << "etime out No."<<pid<<" "<< endl;
}
else if (res == 0)
{
pthread_mutex_unlock(&mutex);
cout << "res = 0." << "No."<<pid<<endl;
break;
}
else
{
pthread_mutex_unlock(&mutex);
cout << "res = " << res << endl;
}
}
cout << "thread: " + to_string(pid) + " exit." << endl;
return nullptr;
}
线程不能全部退出,原因有两个,一个是锁加的的有问题,可能会导致死锁。
第二个原因,pthread_self();函数调用会占用线程调用(接收cond)时机。因此,建议pthread_self在循环外调用。
上面的代码在我的环境里可以正常运行。可以试一下,如有问题提出来;