- 论坛徽章:
- 0
|
从csdn上找来的答案,问题答案一样,解决办法不一样
楼上面的答案还是没编译过去,唉~~
#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
class Thread
{
private:
int number;
pthread_t tid[2];
public:
Thread()
{
number = 1;
pthread_create(&tid[1], NULL, thread1_ex, this);
pthread_create(&tid[2], NULL, thread2_ex, this);
}
~Thread()
{
cout << "tid1 is " << tid[1] << " tid2 is " << tid[2] << endl;
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
}
static void* thread1_ex(void* pVoid)
{
Thread* p = (Thread*)pVoid;
p->thread1();
return p;
}
static void* thread2_ex(void* pVoid)
{
Thread* p = (Thread*)pVoid;
p->thread2();
return p;
}
void* thread1()
{
for(int i = 0; i < 10; i++)
{
cout << "this is thread1, number is " << number++;
cout << " pid is " << getpid() << " id is " << pthread_self() << endl;
}
}
void* thread2()
{
for(int i = 0; i < 10; i++)
{
cout << "this is thread2, number is " << number++;
cout << " pid is " << getpid() << " id is " << pthread_self() << endl;
}
}
};
int main()
{
Thread *th = new Thread();
delete(th);
return 0;
} |
|