23,114
社区成员
发帖
与我相关
我的任务
分享
a()
{
//处理
sem_post(a2b)
}
b()
{
sem_wait(a2b)
//处理
sem_post(b2c)
}
c()
{
sem_wait(b2c)
//处理
sem_post(c2d)
}
d()
{
sem_wait(c2d)
//处理
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
char dataA[64];
char dataB[64];
char dataC[64];
char dataD[64];
void *worker_A(void *arg)
{
strncpy(dataA, "AAAA", 10);
printf("workA: %s\n", dataA);
pthread_exit((void *)&dataA);
}
void *worker_B(void *arg)
{
char *ret;
pthread_join(*((pthread_t *)arg), (void **)&ret);
sprintf(dataB, "%s, BBBB", ret);
printf("workB: %s\n", dataB);
pthread_exit((void *)&dataB);
}
void *worker_C(void *arg)
{
char *ret;
pthread_join(*((pthread_t *)arg), (void **)&ret);
sprintf(dataC, "%s, CCCC", ret);
printf("workC: %s\n", dataC);
pthread_exit((void *)&dataC);
}
void *worker_D(void *arg)
{
char *ret;
pthread_join(*((pthread_t *)arg), (void **)&ret);
sprintf(dataD, "%s, DDDD", ret);
printf("workD: %s\n", dataD);
pthread_exit((void *)&dataD);
}
int main()
{
pthread_t tidA, tidB, tidC, tidD;
int i;
for (i = 0; i < 10; i ++) {
if (pthread_create(&tidA, NULL, worker_A, NULL)) {
fprintf(stderr, "pthread_create error.");
exit(EXIT_FAILURE);
}
if (pthread_create(&tidB, NULL, worker_B, (void *)&tidA)) {
fprintf(stderr, "pthread_create error.");
exit(EXIT_FAILURE);
}
if (pthread_create(&tidC, NULL, worker_C, (void *)&tidB)) {
fprintf(stderr, "pthread_create error.");
exit(EXIT_FAILURE);
}
if (pthread_create(&tidD, NULL, worker_D, (void *)&tidC)) {
fprintf(stderr, "pthread_create error.");
exit(EXIT_FAILURE);
}
pthread_join(tidD, (void **)NULL);
}
return EXIT_SUCCESS;
}