Linux 多线程的使用
工具: clion、cmake
平台:Ubuntu
在使用 多线程时出现以下错误:
/usr/include/c++/9/thread:126: undefined reference to `pthread_create'
解决方案:在camkelist 文件中设置 g++
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")
多线程
代码:
//
// Created by ly on 2022/8/2.
//
#include <iostream>
#include <thread>
#include <pthread.h>
void test1(){
std::cout << "child thread test" << std::endl;
}
void test2(){
std::thread t(test1);
t.join();
}
void *test4(void* args){
std::cout<< "child pthread test" << std::endl;
return 0;
}
// 线程的运行函数
void* say_hello(void* args)
{
std::cout << "Hello Runoob!" << std::endl;
return 0;
}
void test3(){
//定义线程的ID变量,多个变量使用 数组
pthread_t tId;
//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
//int ret = pthread_create(&tId, NULL, reinterpret_cast<void *(*)(void *)>(test1), NULL);
int ret = pthread_create(&tId, NULL, test4, NULL);
pthread_exit(NULL);
}
int main(){
test2();
std::cout << "hello world" << std::endl;
return 1;
}
cmakelist.txt:
cmake_minimum_required(VERSION 3.17)
project(MultipleThreadTest)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")
add_executable(MultipleThreadTest main.cpp main.cpp)
C++ 11 Thread
使用标准库 下的多线程
//
// Created by ly on 2022/8/2.
//
#include <iostream>
#include <thread>
void test1(){
std::cout << "child thread test" << std::endl;
}
void test2(){
std::thread t(test1);
t.join();
}
int main(){
test2();
std::cout << "hello world" << std::endl;
return 1;
}
运行结果:
POSIX Threads
使用 POSIX 编写多线程 C++ 程序
//
// Created by ly on 2022/8/2.
//
#include <iostream>
#include <pthread.h>
void *test4(void* args){
std::cout<< "child pthread test" << std::endl;
return 0;
}
// 线程的运行函数
void* say_hello(void* args)
{
std::cout << "Hello Runoob!" << std::endl;
return 0;
}
void test3(){
//定义线程的ID变量,多个变量使用 数组
pthread_t tId;
//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
//int ret = pthread_create(&tId, NULL, reinterpret_cast<void *(*)(void *)>(test1), NULL);
int ret = pthread_create(&tId, NULL, test4, NULL);
pthread_exit(NULL);
}
int main(){
test3();
std::cout << "hello world" << std::endl;
return 1;
}
运行结果:
reinterpret_cast 类型转换
如果定义的函数不一致 ,C++提供了reinterpret_cast用于任意类型的转换。
语法:reinpreter_cast<type-id> (exp)
其中, reinterpret_cast后的尖括号中的type-id类型必须是一个指针、引用、算术类型、函数指针或者成员指针。它可以把一个指针转换成一个整数,也可以把一个整数转换成一个指针。
例如:
reinterpret_cast<void *(*)(void *)>(test1)