c++ 11 提供了基础的 多线程同步语句,也就是: 互斥锁,条件变量,异步,原子锁
信号量机制是LInux POXIS 中的标准的。这个需要注意。
方法1(c),信号量
这个是.c文件,如果是.cpp,因为类型转换更加严格,所以需要改一下。
//使用信号量实现多线程的顺序执行
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
sem_t sem_a, sem_b, sem_c;
void *fun_a() {
while (1) {
sem_wait(&sem_a);
printf("A");
sem_post(&sem_b);
}
}
void *fun_b() {
while (1) {
sem_wait(&sem_b);
printf("B");
sem_post(&sem_c);
}
}
void *fun_c() {
while (1) {
sem_wait(&sem_c);
printf("C\n");
sem_post(&sem_a);
}
}
int main() {
sem_init(&sem_a, 0, 1);
sem_init(&sem_b, 0, 0);
sem_init(&sem_c, 0, 0);
pthread_t thread_a, thread_b, thread_c;
pthread_create(&thread_a, NULL, fun_a, NULL);
pthread_create(&thread_b, NULL, fun_b, NULL);
pthread_create(&thread_c, NULL, fun_c, NULL);
while (1);
return 0;
}
方法1(cpp)
//使用信号量实现多线程的顺序执行
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
sem_t sem_a, sem_b, sem_c;
static void *fun_a(void*) {
while (1) {
sem_wait(&sem_a);
printf("A");
sem_post(&sem_b);
}
}
static void *fun_b(void*) {
while (1) {
sem_wait(&sem_b);
printf("B");
sem_post(&sem_c);
}
}
static void *fun_c(void*) {
while (1) {
sem_wait(&sem_c);
printf("C\n");
sem_post(&sem_a);
}
}
int main() {
sem_init(&sem_a, 0, 1);
sem_init(&sem_b, 0, 0);
sem_init(&sem_c, 0, 0);
pthread_t thread_a, thread_b, thread_c;
pthread_create(&thread_a, NULL, fun_a, NULL);
pthread_create(&thread_b, NULL, fun_b, NULL);
pthread_create(&thread_c, NULL, fun_c, NULL);
while (1);
return 0;
}