概述
//使用互斥锁同步线程
#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 errorn");
exit(1);
}
if(pthread_create(&thr_id2, NULL, thrd_func2, NULL) != 0)
{
printf("Create thread2 errorn");
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 = %dn", 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 = %dn", 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 failn", no);
exit(1);
}
else
{
printf("Create thread %d successn", no);
}
}
for(no = 0; no < THREAD_NUM; no++)
{
if(pthread_join(thread[no], &tret) != 0)
{
printf("join thread %d errorn", no);
exit(1);
}
else
{
printf("Join thread %d successn", 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;
}
最后
以上就是怕黑睫毛为你收集整理的linux互斥锁的应用的全部内容,希望文章能够帮你解决linux互斥锁的应用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复