ubuntu 下qt creator 比 codeblocks 更好用。然而vs比qt creator 好用很多,可是win不支持pthread.h。qt creator缺点是要配置一下才能输入中文。谷歌一下就行。超级无敌爽。至于vim,应该是ide装vim插件,利用vim的普通模式,而不是vim装ide打功能。。。vim有时编译不好,像多线程链接就要加上pthread,用vim的话没用工程配置的概念。
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#define MAX 1000
pthread_mutex_t the_mutex;//互斥量
pthread_cond_t condc,condp;//条件变量
int buffer=0;//缓冲内容
void *producer(void *ptr)
{
for(int i=1;i<=MAX;i++)
{
pthread_mutex_lock(&the_mutex);//互斥使用缓冲区
while(buffer!=0)
{
pthread_cond_wait(&condp,&the_mutex);//阻塞以等待信号
}
buffer=i;
printf("producer %d\n",i);
pthread_cond_signal(&condc);//向另一个进程发出信号唤醒
pthread_mutex_unlock(&the_mutex);//释放缓冲区
}
pthread_exit(0);
}
void *consumer(void *ptr)
{
int i;
for(i=1;i<=MAX;i++)
{
pthread_mutex_lock(&the_mutex);
while(buffer==0)
pthread_cond_wait(&condc,&the_mutex);
printf("consumer %d\n",buffer);
buffer=0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main()
{
pthread_t pro,con;//线程号
pthread_mutex_init(&the_mutex,0);//创建一个互斥变量
pthread_cond_init(&condc,0);//创建一个条件变量
pthread_cond_init(&condp,0);
pthread_create(&con,0,consumer,NULL);//创建线程
pthread_create(&pro,0,producer,NULL);
pthread_join(pro,0);//如果没有pthread_join;主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了
pthread_join(con,0);//加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行
//pthread_join函数会让主线程阻塞,直到所有线程都已经退出
pthread_cond_destroy(&condc);//销毁条件变量
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);//销毁互斥变量
}