在Linux环境下使用C++进行多线程编程,通常会用到C++11标准库中的<thread>头文件,它提供了一些基本的线程管理功能。以下是一个简单的例子,展示了如何创建和运行多个线程:
#include <iostream>
#include <thread>
// 线程函数
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建线程
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout << "Thread has finished execution." << std::endl;
return 0;
}
在这个例子中,我们首先包含了<thread>头文件,然后定义了一个将在新线程中执行的函数helloFunction。在main函数中,我们使用std::thread创建了一个新线程,并将helloFunction作为参数传递给它。t.join()调用会阻塞main函数,直到t线程执行完毕。
如果你想要在线程中传递参数,可以这样做:
#include <iostream>
#include <thread>
// 线程函数,接受两个参数
void addFunction(int a, int b) {
std::cout << "The sum is " << a + b << std::endl;
}
int main() {
// 创建线程,并传递参数
std::thread t(addFunction, 5, 7);
// 等待线程完成
t.join();
std::cout << "Thread has finished execution." << std::endl;
return 0;
}
在多线程编程中,还需要注意线程同步的问题,以避免竞态条件和数据不一致。C++标准库提供了多种同步机制,如互斥锁std::mutex、条件变量std::condition_variable、原子操作std::atomic等。
下面是一个使用互斥锁来保护共享资源的例子:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 创建一个互斥锁
void printMessage(const std::string& msg) {
mtx.lock(); // 锁定互斥锁
std::cout << msg << std::endl;
mtx.unlock(); // 解锁互斥锁
}
int main() {
std::thread t1(printMessage, "Hello from thread 1");
std::thread t2(printMessage, "Hello from thread 2");
t1.join();
t2.join();
return 0;
}
在这个例子中,我们定义了一个互斥锁mtx,并在printMessage函数中使用lock()和unlock()方法来保护对std::cout的访问,确保每次只有一个线程可以打印消息。
多线程编程是一个复杂的主题,涉及到许多高级概念,如死锁、活锁、饥饿、线程池、并发数据结构等。在实际应用中,需要仔细设计和管理线程间的交互,以确保程序的正确性和性能。