pthread linux mutet:example1

Posted 在左手

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pthread linux mutet:example1相关的知识,希望对你有一定的参考价值。

#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的主要内容,如果未能解决你的问题,请参考以下文章

Linux中的pthread概念

Linux C++ pthread是什么缩写?(POSIX Threads)<pthread.h>

linux下多线程之pthread_detach(pthread_self())

linux创建线程之pthread_create

windows 下有没有类似linux中的pthread_detach,pthread_join和pthread_joinable函数

除了 pthread_create 在 linux 上创建 linux 线程的方法