线程同步手段:互斥锁,读写锁,条件变量。
本文实例利用条件变量保持读写同步
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#define THREAD_SYNC_PROTECT
struct msg {
struct msg *m_next;
char context[100];
};
struct msg *workq = NULL;
int flag = 1;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
void process_msg(void)
{
struct msg *mp = NULL;
for (;;) {
#if defined THREAD_SYNC_PROTECT
/* protect condition varialbe without missing any condition change */
pthread_mutex_lock(&qlock);
while (workq == NULL) {
/* append thread to wait queue and make thread sleep, finally unlock mutex */
pthread_cond_wait(&qready, &qlock);
/* relock mutex when function "pthread_cond_wait" returns */
printf("condition match!\n");
}
#endif
if (workq != NULL) {
mp = workq;
workq = mp->m_next;
}
#if defined THREAD_SYNC_PROTECT
pthread_mutex_unlock(&qlock);
#endif
if (workq != NULL) {
/* process message */
printf("thread %u :receive message %s\n", pthread_self(), mp->context);
free(mp);
}
}
}
void enqueue_msg(struct msg *mp)
{
/* Get right to operate queue */
pthread_mutex_lock(&qlock);
mp->m_next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
void send_msg(void)
{
int i;
for (i = 0; i < 10; i++) {
struct msg *mp = malloc(sizeof(struct msg));
if (NULL == mp) {
printf("malloc failed!\n");
break;
}
sprintf(mp->context, "%s[%d] request", "customer", i);
enqueue_msg(mp);
sleep(1);
}
flag = 0;
}
int main(void)
{
pthread_t tid_send, tid_process1, tid_process2;
int ret ;
pthread_mutex_init(&qlock, NULL);
ret = pthread_create(&tid_process2, NULL, process_msg, NULL);
if (ret != 0) {
printf("create pthread send_msg failed!\n");
return -1;
}
ret = pthread_create(&tid_process1, NULL, process_msg, NULL);
if (ret != 0) {
printf("create pthread send_msg failed!\n");
return -1;
}
ret = pthread_create(&tid_send, NULL, send_msg, NULL);
if (ret != 0) {
printf("create pthread send_msg failed!\n");
return -1;
}
while(flag);
return 0;
}