#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex;
static int tickets = 100;
void *thrd_func1(void *arg);
void *thrd_func2(void *arg);
int main()
{
pthread_t thr_id1;
pthread_t thr_id2;
void *ret1;
void *ret2;
pthread_mutex_init(&mutex, NULL);
if(pthread_create(&thr_id1, NULL, thrd_func1, NULL) != 0)
{
printf("Create thread1 error\n");
exit(1);
}
if(pthread_create(&thr_id2, NULL, thrd_func2, NULL) != 0)
{
printf("Create thread2 error\n");
exit(1);
}
if(pthread_join(thr_id1, &ret1) != 0)
{
printf("Join thr1 error!\n");
exit(1);
}
if(pthread_join(thr_id2, &ret2) != 0)
{
printf("Join thr2 error!\n");
exit(1);
}
pthread_mutex_destroy(&mutex);
return 0;
}
void *thrd_func1(void *arg)
{
while(tickets > 0)
{
pthread_mutex_lock(&mutex);
if(tickets <= 0)
break;
printf("thr1 tickets = %d\n", tickets--);
pthread_mutex_unlock(&mutex);
usleep(100000);
}
pthread_exit(NULL);
}
void *thrd_func2(void *arg)
{
while(tickets > 0)
{
pthread_mutex_lock(&mutex);
if(tickets <= 0)
break;
printf("thr2 tickets = %d\n", tickets--);
pthread_mutex_unlock(&mutex);
usleep(100000);
}
pthread_exit(NULL);
}
//多个信息号量控制多个线程
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define THREAD_NUM 3
#define REPEAT_TIMES 5
#define DELAY 4
sem_t sem[THREAD_NUM];
void *thrd_func(void *arg);
int main(void)
{
pthread_t thread[THREAD_NUM];
int no;
void *tret;
for(no = 0; no < THREAD_NUM - 1; no++)
{
sem_init(&sem[no], 0, 0);
}
sem_init(&sem[2], 0, 1);
for(no = 0; no < THREAD_NUM; no++)
{
if(pthread_create(&thread[no], NULL, thrd_func, (void *)no) != 0)
{
printf("Create thread %d fail\n", no);
exit(1);
}
else
{
printf("Create thread %d success\n", no);
}
}
for(no = 0; no < THREAD_NUM; no++)
{
if(pthread_join(thread[no], &tret) != 0)
{
printf("join thread %d error\n", no);
exit(1);
}
else
{
printf("Join thread %d success\n", no);
}
}
for(no = 0; no < THREAD_NUM; no++)
{
sem_destroy(&sem[no]);
}
return 0;
}
void *thrd_func(void *arg)
{
int thrd_num = (int )arg;
sem_wait(&sem[thrd_num]);
printf("Thread %d is starting.\n",thrd_num);
sleep(1);
sem_post(&sem[(thrd_num+THREAD_NUM-1)%THREAD_NUM]);
return (void *)arg;
}