交替打印ABC
使用信号量实现线程同步,分别创建三个子线程,让子线程按照一定的顺序依次执行。
#include <string>
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
sem_t ab, bc, ca;
void print(const string &msg, sem_t &cm, sem_t &nm)
{
for (int i = 0; i < 10;)
{
sem_wait(&cm);
cout << pthread_self() << " print " << msg << endl;
++i;
sem_post(&nm);
}
}
void *printA(void *args)
{
print("A", ab, bc);
return NULL;
}
void *printB(void *args)
{
print("B", bc, ca);
return NULL;
}
void *printC(void *args)
{
print("C", ca, ab);
return NULL;
}
int main()
{
sem_init(&ab, 0, 1);
sem_init(&bc, 0, 0);
sem_init(&ca, 0, 0);
int vals[3];
sem_getvalue(&ab, &vals[0]);
sem_getvalue(&bc, &vals[1]);
sem_getvalue(&ca, &vals[2]);
cout << endl;
for (int i : vals)
cout << i << " ";
cout << endl << endl;
pthread_t tids[3];
pthread_create(&tids[0], nullptr, printA, nullptr);
pthread_create(&tids[1], nullptr, printB, nullptr);
pthread_create(&tids[2], nullptr, printC, nullptr);
pthread_join(tids[0], nullptr);
pthread_join(tids[1], nullptr);
pthread_join(tids[2], nullptr);
sem_getvalue(&ab, &vals[0]);
sem_getvalue(&bc, &vals[1]);
sem_getvalue(&ca, &vals[2]);
cout << endl;
for (int i : vals)
cout << i << " ";
cout << endl << endl;
sem_destroy(&ab);
sem_destroy(&bc);
sem_destroy(&ca);
}
|