#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include <stdlib.h>
#include <sys/time.h>
#define MAX_THREAD_NUM 2
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread_fun(void* arg)
{
int index = *(int*)arg;
struct timespec abstime;
struct timeval now;
gettimeofday(&now,NULL);//获取系统时间
abstime.tv_sec = now.tv_sec + 20;
abstime.tv_nsec = now.tv_usec * 1000;
printf("[%d]thread start up!\n", index);
pthread_mutex_lock(&mutex);
printf("[%d]thread wait...\n", index);
pthread_cond_timedwait(&cond, &mutex, &abstime);
printf("[%d]thread wake up\n", index);
pthread_mutex_unlock(&mutex);
printf("[%d]thread exit!\n", index);
pthread_exit(0);
}
int main()
{
pthread_t tid[MAX_THREAD_NUM];
for(int i = 0; i < MAX_THREAD_NUM; i++)
{
pthread_create(&tid[i], NULL, thread_fun, &i);
sleep(0);
}
printf("--------before 15S--------\n");
sleep(15);
printf("--------after 15S--------\n");
pthread_cond_broadcast(&cond);
sleep(0);
for(int i = 0; i < MAX_THREAD_NUM; ++i)
{
printf("[%d]pthread_join\n", i);
pthread_join(tid[i], NULL);
}
return 0;
}
/*
now.tv_sec + 10的情况
[0]thread start up!
[0]thread wait...
[1]thread start up!
[1]thread wait...
--------before 15S--------
[0]thread wake up
[0]thread exit!
[1]thread wake up
[1]thread exit!
--------after 15S--------
[0]pthread_join
[1]pthread_join
**************
now.tv_sec + 20的情况
[0]thread start up!
[0]thread wait...
[1]thread start up!
[1]thread wait...
--------before 15S--------
--------after 15S--------
[0]thread wake up
[0]pthread_join
[0]thread exit!
[1]thread wake up
[1]thread exit!
[1]pthread_join
//pthread_join一般是主线程来调用,用来等待子线程退出,因为是等待,所以是阻塞的,一般主线程会依次join所有它创建的子线程。
//pthread_exit一般是子线程调用,用来结束当前线程。
//子线程可以通过pthread_exit传递一个返回值,而主线程通过pthread_join获得该返回值,从而判断该子线程的退出是正常还是异常文章来源:https://www.toymoban.com/news/detail-467759.html
精确级别:纳秒级别
struct timespec
//精确到纳秒
{
time_t tv_sec; //秒
long tv_nsec;//纳秒,1s = 1000ms(毫秒) = 1000*1000us(微妙) = 1000*1000*1000ns(纳秒)
}
精确级别:微妙级别
struct timeval
{
time_t tv_sec; //秒
long tv_usec;//微妙,1s = 1000ms(毫秒) = 1000*1000us(微妙) = 1000*1000*1000ns(纳秒)
};
*/
文章来源地址https://www.toymoban.com/news/detail-467759.html
到了这里,关于pthread_mutex的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!