码迷,mamicode.com
首页 > 系统相关 > 详细

pthread linux mutet:example1

时间:2018-04-01 21:50:38      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:col   while   linu   ase   div   star   pac   number   creat   

#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<string>
using namespace std;


#define START 1
#define END 0
int status = START;
void* queuewhile(void *);
void* dosomething(void *);
pthread_mutex_t mutex;
int main()
{
    //int status = START;
    cout << "please,enter something, if the number is larger.the process ends"<<endl;
    pthread_t thread1, thread2;
    sleep(2);
    pthread_mutex_init(&mutex, NULL);
    string strMsg = "hello,world";
    pthread_create(&thread1, NULL, queuewhile,(void*)strMsg.c_str());
    pthread_create(&thread2, NULL, dosomething, NULL);
    pthread_join(thread1, NULL);
    pthread_mutex_destroy(&mutex);
    cout << "the process is closing"<<endl;
    return 0;
}
void* dosomething(void *)
{
    int a = 16;
    int b = 0;
    while(cin >> b)
    {
        pthread_mutex_lock(&mutex);
        cout<< "something happened"<< endl;
        if(b>a)
        {
            cout<< "now,we shut down!"<<endl;
            status = END;
        }else
        {
            cout<< "ops, we just keep go on!"<<endl;
        }
        pthread_mutex_unlock(&mutex);
    }
}


void* queuewhile(void *msg)
{
    string strMsg = (char*)msg;
    if(strMsg.empty())
    {
        cout<< "there no thing"<< endl;
    }else
    {
        while(status)
        {
            pthread_mutex_lock(&mutex);
            cout<<strMsg<<endl;
            pthread_mutex_unlock(&mutex);
            sleep(1);
        }
        //cout << strMsg<<endl;
    }
}

 g++ -o test domything.cpp -lpthread

pthread linux mutet:example1

标签:col   while   linu   ase   div   star   pac   number   creat   

原文地址:https://www.cnblogs.com/zhangdewang/p/8688222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!