您的位置:首页 > 编程语言 > C语言/C++

C语言多线程编程《3个足球运动员》

2015-01-27 14:00 459 查看
场景: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息