#include <pthread.h>
#include <iostream>
class InfoPrinted
{
public:
InfoPrinted(char c,int n):_c(c),_n(n){}
void Show()const {for(int i=0;i<_n;i++)std::cerr<<_c;}
private:
char _c;
int _n;
};
void* PrintInfo(void* Info)
{
InfoPrinted* p=reinterpret_cast<InfoPrinted*>(Info);
if(p) p->Show();
return NULL;
}
int main()
{
pthread_t tid1,tid2;
InfoPrinted* p=new InfoPrinted('a',100);
pthread_create(&tid1,NULL,&PrintInfo,reinterpret_cast<void*>(p));
InfoPrinted* q=new InfoPrinted('z',100);
pthread_create(&tid2,NULL,&PrintInfo,reinterpret_cast<void*>(q));
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);//pthread_join让主线程等待子线程结束之后再结束
return 0;
}
第一次学习多线程编程。注意多线程函数返回值和参数均为哑型指针void*,若要传多个数据进去就要打包成一个结构体,再用指针转换函数reinterpret_cast<>()来进行转换。pthread_create()的四个参数分别为指向某线程的指针,NULL,线程函数和其参数。pthread_join可以让主线程等待子线程结束后再结束(否则主线程直接结束,子线程无法调用主线程数据);