//Linux 信号量的简单实用
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <semaphore.h>
#include <pthread.h>
//int sem_init(sem_t *sem, int pshared, unsigned int value);
//int sem_destroy(sem_t *sem);
//int sem_wait(sem_t *sem);
//int sem_trywait(sem_t *sem);
//int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
sem_t sem;
void *func1(void *arg)
{
struct timespec t1;
struct timeval time1;
gettimeofday(&time1, NULL);
t1.tv_sec = time1.tv_sec+6;
int *running = (int *)arg;
printf("thread func1 running : %d\n", *running);
while(1){
printf("thread func1 running.......11111\n");
//sem_wait(&sem);
//sem_trywait(&sem);
sem_timedwait(&sem, &t1);
printf("thread func1 running.......22222\n");
//sleep(2);
gettimeofday(&time1, NULL);
t1.tv_sec = time1.tv_sec+6;
sem_post(&sem);
printf("thread func1 running.......post\n");
sleep(1);
}
pthread_exit(NULL);
}
void *func2(void *arg)//ui
{
struct timespec t2;
struct timeval time2;
gettimeofday(&time2, NULL);
t2.tv_sec = time2.tv_sec+3;
int *running = (int *)arg;
printf("thread func2 running : %d\n", *running);
while(1){
printf("thread func2 running.......33333\n");
//sem_wait(&sem);
//sem_trywait(&sem);
sem_timedwait(&sem, &t2);
printf("thread func2 running.......44444\n");
gettimeofday(&time2, NULL);
t2.tv_sec = time2.tv_sec+3;
//sem_post(&sem);
sleep(1);
}
pthread_exit(NULL);
}
int main(void)
{
int a = 1;
sem_init(&sem, 0, 1);
pthread_t thread_id[2];
pthread_create(&thread_id[0], NULL, func1, (void *)&a);
//sleep(10);
a = 2;
pthread_create(&thread_id[1], NULL, func2, (void *)&a);
printf("main thread running.\n");
pthread_join(thread_id[0], NULL);
pthread_join(thread_id[1], NULL);
sem_destroy(&sem);
return 0;
}