在Linux环境下进行C++多线程编程,主要使用C++11标准库中的<thread>
头文件提供的功能。以下是一些基本步骤和示例代码,帮助你开始使用C++进行多线程编程。
首先,你需要包含<thread>
头文件。
#include <iostream>
#include <thread>
使用std::thread
类来创建线程。你可以将一个函数或可调用对象传递给std::thread
的构造函数。
#include <iostream>
#include <thread>
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建一个线程,执行helloFunction函数
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout << "Hello from main!" << std::endl;
return 0;
}
#include <iostream>
#include <thread>
int main() {
// 创建一个线程,执行lambda表达式
std::thread t([]() {
std::cout << "Hello from a thread!" << std::endl;
});
// 等待线程完成
t.join();
std::cout << "Hello from main!" << std::endl;
return 0;
}
你可以将参数传递给线程函数。
#include <iostream>
#include <thread>
void greet(std::string name) {
std::cout << "Hello, " << name << " from a thread!" << std::endl;
}
int main() {
std::string name = "Alice";
// 创建一个线程,传递参数name
std::thread t(greet, name);
// 等待线程完成
t.join();
std::cout << "Hello from main!" << std::endl;
return 0;
}
多线程编程中,线程同步是一个重要的问题。C++提供了多种同步机制,如互斥锁(std::mutex
)、条件变量(std::condition_variable
)等。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥锁
void printMessage(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();
std::cout << "Hello from main!" << std::endl;
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void printId(int id) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return ready;}); // 等待条件变量
std::cout << "Thread " << id << std::endl;
}
void go() {
std::lock_guard<std::mutex> lck(mtx);
ready = true;
cv.notify_all(); // 通知所有等待的线程
}
int main() {
std::thread threads[10];
// 创建10个线程
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(printId, i);
}
std::cout << "10 threads ready to race..." << std::endl;
go(); // 通知线程开始执行
for (auto &th : threads) {
th.join();
}
std::cout << "All threads finished." << std::endl;
return 0;
}
C++11提供了线程局部存储(thread_local
)关键字,用于声明线程局部变量。
#include <iostream>
#include <thread>
thread_local int counter = 0;
void incrementCounter() {
for (int i = 0; i < 5; ++i) {
++counter;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "Counter in thread: " << counter << std::endl;
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "Counter in main: " << counter << std::endl;
return 0;
}
通过这些基本步骤和示例代码,你可以在Linux环境下使用C++进行多线程编程。多线程编程是一个复杂的话题,涉及到许多高级概念和技术,如线程池、原子操作、内存模型等。建议进一步阅读相关书籍和文档,深入理解多线程编程的原理和实践。