单独创建一个线程并执行

C++并发编程入门 目录

STL 写法

cpp 复制代码
#include <thread>
#include <iostream>
using namespace std;

void thread_fun(void)
{
    cout << "one STL thread!" << endl;
}

int main(void)
{
    std::thread thread1(thread_fun);
    thread1.join();
    
    return 0;
}

其中,如果是创建CMake工程,CMakeLists.txt的内容如下:

cpp 复制代码
cmake_minimum_required(VERSION 3.3)

#create a project
project(cpp_project)

#create exe file
find_package(Threads REQUIRED)
add_executable(main main.cpp)
target_link_libraries(main Threads::Threads)

在Windows上运行

在Ubuntu上运行

解释说明:

1 std::thread

述代码中的线程类 std::thread 是标准库自带的线程类,在C++11中开始提供。

用这个类创建的线程对象的时候,必须提供一个函数(或者仿函数functor)作为线程执行体。所以,一个线程其实就是一个独立执行的函数

这个独立是什么意思呢?后面会看出来。

thread1对象在构造的时候,接受一个普通的C函数作为执行体。

2 join

join是让main函数等待自己,等待线程thread1执行完了main函数再退出。

如果不是这样的话,main函数执行完线程对象创建之后,main函数就继续执行自己的 return 语句去了,main函数就会退出。main函数退出了不得了,整个可执行程序也会被操作系统收回。这样,线程就不能得到完整的执行。

Windows API写法

cpp 复制代码
#include <iostream>
#include <windows.h>
using namespace std;

DWORD WINAPI ThreadFun(LPVOID lpParamter)
{
    cout << "one Windows thread!" << endl;
    return 0;
}

int main()
{

    HANDLE hThread = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);

    //等待线程执行结束
    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(hThread);

    return 0;
}

Linux API写法

g++ HelloCPP.cpp -pthread -o main

cpp 复制代码
#include <pthread.h>
#include <iostream>
using namespace std;

void* thread_fun(void *arg)
{
    cout << "one Linux thread!" << endl;
    return 0;
}

int main(void)
{
    pthread_t thread_id;
    pthread_create(&thread_id, NULL, thread_fun, NULL);
    pthread_join(thread_id, NULL);
    
    return 0;
}
相关推荐
MC皮蛋侠客1 天前
Google Test 单元测试指南
c++·单元测试·google test
方也_arkling1 天前
【Java-Day08】static / final / 枚举
java·开发语言
艾莉丝努力练剑1 天前
【Linux:文件】Ext系列文件系统进阶
linux·运维·服务器·c++·文件系统·文件io·ext
风吹夏回1 天前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei111 天前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1121 天前
web-第一次课后作业
java·开发语言·idea
kkeeper~1 天前
0基础C语言积跬步之数据在内存中的存储
c语言·数据结构·算法
小熊Coding1 天前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋91 天前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
2401_868534781 天前
论企业网络设计
数据结构