linux互斥锁的应用
来源:互联网 发布:英雄美工钢笔 编辑:程序博客网 时间:2024/05/22 02:10
#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;
}
- linux互斥锁的应用
- davinci 的Linux应用
- Linux framebuffer的应用
- Linux中链表的应用
- Linux grep的应用
- 嵌入linux 的广泛应用
- Linux 网络的 IPv6 应用
- Linux网络的IPv6应用
- 简介Linux的一般应用
- linux网络应用的常用命令
- linux下shell的应用
- Linux下Tar的应用
- linux的GPIO应用实例
- linux的一些高级应用
- linux curses 菜色的应用
- Linux中ifconfig的应用
- linux set 命令的应用
- Linux中数组的应用~~~~
- Unity3D Camera.targetTexture 目标纹理
- Phone重绘机制drawRect
- Android layout_weight属性
- stuff函数
- HD陈雄翔13802556180水生垃圾缺德、缺信就是个畜生色狼!
- linux互斥锁的应用
- 雪佛兰科鲁兹掀背车 加入两厢大战
- QML与Qt C++ 交互机制探讨与总结
- Java Socket实战之三 传输对象
- linux socket
- 使用规则引擎建立电力调度运行安全分析系统学习
- 一步一步学Cocos2d-html5做游戏教程(入门篇)
- 有个JVM性能调优--转载帖子
- 转换RTSP, HTTP, UniUDP, MultiUDP协议直播流成RTMP协议直播流的小工具(HTTP转成RTMP案例展示)