环境使用ubuntu18.04,使用POSIX这个库
1.创建一个线程,并执行
2.等待线程结束,并退出主函数。
完整example.cpp代码:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
std::cout << "Thread Function :: Start" << std::endl;
// Sleep for 2 seconds
sleep(2);
std::cout << "Thread Function :: End" << std::endl;
return NULL;
}
int main()
{
// Thread id
pthread_t threadId;
// Create a thread that will function threadFunc()
int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
// Check if thread is created sucessfuly
printf("***********err:\t%d\n",err);
if (err)
{
std::cout << "Thread creation failed : " << strerror(err);
return err;
}
else
std::cout << "Thread Created with ID : " << threadId << std::endl;
// Do some stuff in Main Thread
std::cout << "Waiting for thread to exit" << std::endl;
// Wait for thread to exit
err = pthread_join(threadId, NULL);
// check if joining is sucessful
if (err)
{
std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
return err;
}
std::cout << "Exiting Main" << std::endl;
return 0;
}
编译使用:
g++ example.cpp -lpthread
或cmake,CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(pthread_demo)
add_executable(example example.cpp)
target_link_libraries(example pthread)
此处使用g++,运行后输出如下结果:
./a.out:
有时会碰到线程创建失败的提示:Thread creation failed,有以下两种可能:
1. 系统线程数有限制,或者堆栈大小不够,使用指令查看资源配置的情况:
ulimit -a
ulimit -s 可用于设置堆栈大小,可以开到4M试试,其他选项的配置同理。
2.?pthread_create()函数的使用有问题,将属性的参数放开,或者改为NULL有可能解决问题。
|