多线程小程序

#include <iostream>
#include <pthread.h>
#include <stdio.h>

using namespace std;

int con=5;
pthread_mutex_t task;
pthread_cond_t cond;

void* change(void *args)
{
    usleep(400);
    pthread_t id = pthread_self();
    int i=300;
    pthread_mutex_lock(&task);
    con++;
    cout<<"id=["<<id<<"]"<<"i="<<i<<"con="<<con<<"thread"<<*((int *)args)<<endl;
    pthread_cond_signal(&cond);    
    pthread_mutex_unlock(&task);
    pthread_exit(NULL);
}

int main()
{
    pthread_t id[4];
    pthread_mutex_init(&task,NULL);
    pthread_cond_init(&cond,NULL);
    
    int i;
    int temp[4]={0};
    for(i=0;i<4;i++)
    {
        temp[i]= i;
        int ret=pthread_create(&id[i],NULL,change,(int *)&temp[i]);
        pthread_mutex_lock(&task);
        pthread_cond_wait(&cond,&task);
        con--;
        cout<<"maincon="<<con<<endl;
        pthread_mutex_unlock(&task);
    }
    for(i=0;i<4;i++)
        pthread_join(id[i],NULL);
    pthread_mutex_destroy(&task);
    pthread_cond_destroy(&cond);
}

输出结果:

id=[3074448192]i=300con=6thread0
maincon=5
id=[3066055488]i=300con=6thread1
maincon=5
id=[3056597824]i=300con=6thread2
maincon=5
id=[3048205120]i=300con=6thread3
maincon=5


你可能感兴趣的:(多线程)