C语言多线程编程《3个足球运动员》
2015-01-27 14:00
507 查看
场景:3个足球运动员练习传球。
方法:
1. A传给B,B传给C,C传给A。
2. 如此反复,踢10圈,结束练习。
技术点:
1. 线程的创建,结束,合并。
2. semaphore
编程实例:(Windows VC6.00 Console Application)
#include <pthread.h>
#include <semaphore.h>
#pragma comment(lib, "pthreadVC2.lib")
#define PLAYERNUM 3
sem_t player[PLAYERNUM];
pthread_t pid[PLAYERNUM];
void *play(void *arg);
int main(int argc, char* argv[])
{
int i;
for(i = 0 ; i < PLAYERNUM ; i++) {
sem_init(&player[i], NULL, 0);
pthread_create(&pid[i], NULL, play, (void *)i);
}
sem_post(&player[0]);
for(i = 0 ; i < PLAYERNUM ; i++)
pthread_join(pid[i], NULL);
return 0;
}
void *play(void *arg)
{
int i;
for(i = 0 ; i < 10 ; i++) {
sem_wait(&player[(int)arg]);
printf("%d to %d\n", (int)arg, ((int)arg + 1)%PLAYERNUM);
sem_post(&player[((int)arg + 1)%PLAYERNUM]);
}
pthread_exit(NULL);
return NULL;
}
输出:
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
Press any key to continue
方法:
1. A传给B,B传给C,C传给A。
2. 如此反复,踢10圈,结束练习。
技术点:
1. 线程的创建,结束,合并。
2. semaphore
编程实例:(Windows VC6.00 Console Application)
#include <pthread.h>
#include <semaphore.h>
#pragma comment(lib, "pthreadVC2.lib")
#define PLAYERNUM 3
sem_t player[PLAYERNUM];
pthread_t pid[PLAYERNUM];
void *play(void *arg);
int main(int argc, char* argv[])
{
int i;
for(i = 0 ; i < PLAYERNUM ; i++) {
sem_init(&player[i], NULL, 0);
pthread_create(&pid[i], NULL, play, (void *)i);
}
sem_post(&player[0]);
for(i = 0 ; i < PLAYERNUM ; i++)
pthread_join(pid[i], NULL);
return 0;
}
void *play(void *arg)
{
int i;
for(i = 0 ; i < 10 ; i++) {
sem_wait(&player[(int)arg]);
printf("%d to %d\n", (int)arg, ((int)arg + 1)%PLAYERNUM);
sem_post(&player[((int)arg + 1)%PLAYERNUM]);
}
pthread_exit(NULL);
return NULL;
}
输出:
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
0 to 1
1 to 2
2 to 0
Press any key to continue
相关文章推荐
- 中国足球运动员当然有资格泡妞和逛夜店
- 恋人过早同居的3个悲惨结局
- C++ STL 提供了3个序列容器 :vector, deque, list
- 在XE5中 VCL空窗体的3个线程
- 获取3个数组不重复的值的具体实现
- Linux文件系统-3个重要数据结构及相互间的关系
- 屏幕抓图至少分为3个步骤:
- 利用stm32来产生1M,1K,1Hz的3个方波(转)
- cocos2d(CCSprite 用贝塞尔做抛物线,足球精灵并且同时做旋转放大效果)
- 3个开源TTS(四)eSpeak1.06的源码调试环境vim+vimgdb
- 控件的3个状态
- NBA常识 位置的划分 足球:越位等于抢跑
- 【转】移动web页面支持弹性滚动的3个方案
- C++代码札记(二)猴子吃桃问题、输入10个数字,输出其中最大的3个数字。
- 足球与oracle系列(2):巴西揭幕战预演,oracle体系结构杂谈
- [转] 3个学习Socket编程的简单例子:TCP Server/Client, Select
- 数学教授谈足球博彩:世界杯博彩公司稳赚不赔
- js 只能输入英文和数字,且首位必须是字母,字母总数不能超过3个,总长度不能超过20!
- shell备份文件、重命名文件、删除指定文件的3个脚本分享