#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <iostream>
using namespace std;
void* myThread(void* arg);
int main() {
int ret=0;
pthread_t mythread;
ret=pthread_create(&mythread,NULL,myThread,NULL);
if(ret !=0)
{
printf("Can't create pthread (%s) \n", strerror(errno));
}
int status=0;
pthread_join(ret,(void ** ) status);
cout<<status<<endl;
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
void* myThread(void* arg)
{
printf("Thread ran\n");
printf("fjsdlkjfkdslfkjlsklds");
//pthread_exit(arg);
}
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$ ../Debug/PTthreadeg 0
!!!Hello World!!!
Thread ran
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$ ../Debug/PTthreadeg
0
!!!Hello World!!!
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$ ../Debug/PTthreadeg
0
!!!Hello World!!!
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$ ../Debug/PTthreadeg
0
!!!Hello World!!!
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$ ../Debug/PTthreadeg
Thread ran
0
!!!Hello World!!!
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$ ../Debug/PTthreadeg
0Thread ran
fjsdlkjfkdslfkjlsklds
!!!Hello World!!!
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$ ../Debug/PTthreadeg
0
!!!Hello World!!!
Thread ran
Thread ran
andrewu@andrewu-VirtualBox:~/workspace/cpp/PTthreadeg/src$

本文介绍如何在C++中使用pthread库创建并管理线程,通过简单的示例展示了线程的基本创建、运行及退出过程,并演示了线程间的数据交互。
1万+

被折叠的 条评论
为什么被折叠?



