#include<iostream>
#include<stdio.h>
#include<string.h>
#include<sstream>
#include<unistd.h>
#include<pthread.h>
using namespace std;
pthread_t thread[2];
pthread_mutex_t mut;
int number=0,i;
#define MAX 10
string now()
{
time_t time1=time(NULL);
struct tm * time = localtime(&time1);
std::stringstream oss;
oss<<time->tm_min<<":"<<time->tm_sec;
return oss.str();
}
void *thread1(void*)
{
cout<<"thread1:I am thread1"<<endl;
for(i=0;i<MAX;i++)
{
cout<<now()<<":thread1:number="<<number<<",i="<<i<<endl;
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(2);
}
cout<<"thread1:mainthread wait me?"<<endl;
pthread_exit(NULL);
}
void *thread2(void*)
{
cout<<"thread2:I am thread2"<<endl;
for(i=0;i<MAX;i++)
{
cout<<now()<<":thread2:number="<<number<<",i="<<i<<endl;
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(3);
}
cout<<"thread2:mainthread wait me?"<<endl;
pthread_exit(NULL);
}
void thread_create(void)
{
int temp;
memset(&thread,0,sizeof(thread));
if((temp=pthread_create(&thread[0],NULL,thread1,NULL))!=0)
cout<<"thread1 create fail!" <<endl;
else
cout<<"thread1 create!"<<endl;
if((temp=pthread_create(&thread[1],NULL,thread2,NULL))!=0)
cout<<"thread2 create fail!" <<endl;
else
cout<<"thread2 create!"<<endl;
}
void thread_wait(void)
{
if(thread[0]!=0)
{
pthread_join(thread[0],NULL);
cout<<"thread1 finish!"<<endl;
}
if(thread[1]!=0)
{
pthread_join(thread[1],NULL);
cout<<"thread2 finish!"<<endl;
}
}
int main()
{
pthread_mutex_init(&mut,NULL);
cout<<"I am mainthread! now create child thread!"<<endl;
thread_create();
cout<<"I am mainthread! now wait child thread exit!"<<endl;
thread_wait();
return 0;
}
g++ -lpthread multhread.cpp -o multhread_test
//第1次运行结果
./multhread_test
I am mainthread! now create child thread!
thread1 create!
thread2 create!
I am mainthread! now wait child thread exit!
thread1:I am thread1
thread2:I am thread2
3:40:thread1:number=0,i=0
3:40:thread2:number=0,i=0
3:42:thread1:number=2,i=1
3:43:thread2:number=3,i=2
3:44:thread1:number=4,i=3
3:46:thread2:number=5,i=4
3:46:thread1:number=6,i=5
3:48:thread1:number=7,i=6
3:49:thread2:number=8,i=7
3:50:thread1:number=9,i=8
3:52:thread2:number=10,i=9 //这个时间thread1和thread2都有可能会被运行,但只会运行其一
thread1:mainthread wait me?
thread1 finish!
thread2:mainthread wait me?
thread2 finish!
//第2次运行结果
./multhread_test
I am mainthread! now create child thread!
thread1 create!
thread2 create!
I am mainthread! now wait child thread exit!
thread1:I am thread1
19:3:thread1:number=0,i=0
thread2:I am thread2
19:3:thread2:number=1,i=0
19:5:thread1:number=2,i=1
19:6:thread2:number=3,i=2
19:7:thread1:number=4,i=3
19:9:thread1:number=5,i=4
19:9:thread2:number=6,i=5
19:11:thread1:number=7,i=6
19:12:thread2:number=8,i=7
19:13:thread1:number=9,i=8
19:15:thread1:number=10,i=9
thread2:mainthread wait me?
thread1:mainthread wait me?
thread1 finish!
thread2 finish!