#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