条件变量:
#include <stdio.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/epoll.h>
struct msg{
int num;
struct msg *next;
};
struct msg *head;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t has_data = PTHREAD_COND_INITIALIZER;
void *produser(void *arg){
while(1){
struct msg *mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("---produce : %d\n", mp->num);
pthread_mutex_lock(&mutex);
mp->next = head;
head = mp;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&has_data);
sleep(rand() % 3);
}
return NULL;
}
void *consumer(void *arg){
while(1){
struct msg *mp;
pthread_mutex_lock(&mutex);
if(head == NULL) pthread_cond_wait(&has_data, &mutex);
mp = head;
head = mp->next;
pthread_mutex_unlock(&mutex);
printf("--------consumer : %d\n", mp->num);
free(mp);
sleep(rand() % 3);
}
return NULL;
}
int main(){
srand(time(NULL));
int ret;
pthread_t pid, cid;
ret = pthread_create(&pid, NULL, produser, NULL);
ret = pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
return 0;
}
信号量:
#include <stdio.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/epoll.h>
#include <semaphore.h>
#define NUM 5
int queue[NUM];
sem_t blank_number, product_number;
void *producer(void *arg){
int i = 0;
while(1){
sem_wait(&blank_number);
queue[i] = rand() % 1000 + 1;
printf("----Produce---%d\n", queue[i]);
sem_post(&product_number);
i = (i + 1) % NUM;
sleep(0);
}
}
void *consumer(void *arg){
int i = 0;
while(1){
sem_wait(&product_number);
printf("Consume---%d\n", queue[i]);
queue[i] = 0;
sem_post(&blank_number);
i = (i + 1) % NUM;
sleep(rand() % 3);
}
}
int main(){
pthread_t pid, cid;
sem_init(&blank_number, 0, NUM);
sem_init(&product_number, 0, 0);
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
sem_destroy(&blank_number);
sem_destroy(&product_number);
return 0;
}