本文介绍Linux应用编程中的线程同步方法,具体来讲是使用信号量和两个线程实现了一个简单的生产者消费者模型。
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <semaphore.h>
#define errExit(err, msg) \
do { errno = err; perror(msg); \
exit(EXIT_FAILURE); } while(0)
sem_t consumer_ready;
sem_t producer_ready;
int count;
void *__producer_thread_func(void *arg)
{
char *name = "producer";
int ret;
ret = prctl(PR_SET_NAME, (unsigned long)name, NULL, NULL, NULL);
if(ret < 0) {
perror("prctl PR_SET_NAME");
exit(EXIT_FAILURE);
}
count = 0;
while(1) {
sem_wait(&consumer_ready);
sleep(1);
count++;
printf("producer: %d\n", count);
sem_post(&producer_ready);
}
}
void *__consumer_thread_func(void *arg)
{
char *name = "consumer";
int ret;
ret = prctl(PR_SET_NAME, (unsigned long)name, NULL, NULL, NULL);
if(ret < 0) {
perror("prctl PR_SET_NAME");
exit(EXIT_FAILURE);
}
while(1) {
sem_wait(&producer_ready);
count--;
printf("consumer: %d\n", count);
sem_post(&consumer_ready);
}
}
int main()
{
pthread_t thread_producer;
pthread_t thread_consumer;
int ret;
ret = sem_init(&producer_ready, 0, 0);
if(ret < 0) {
perror("sem producer_ready");
return -1;
}
ret = sem_init(&consumer_ready, 0, 1);
if(ret < 0) {
perror("sem consumer_ready");
return -1;
}
ret = pthread_create(&thread_producer, NULL, __producer_thread_func, NULL);
if(ret) {
errExit(ret, "create producer");
}
ret = pthread_create(&thread_consumer, NULL, __consumer_thread_func, NULL);
if(ret) {
errExit(ret, "create consumer");
}
pthread_join(thread_producer, NULL);
pthread_join(thread_consumer, NULL);
printf("test end\n");
return 0;
}
上面的程序中,生产者每一秒钟将count加1,消费者将count减1
运行的结果是生产者打印1,消费者打印0.