在Ubuntu上使用C++实现多线程,通常会使用C++11标准库中的<thread>头文件。以下是一个简单的例子,展示了如何在C++中创建和使用线程:
#include <iostream>
#include <thread>
// 线程函数
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建一个线程
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout << "Hello from the main function!" << std::endl;
return 0;
}
在这个例子中,我们首先包含了<thread>头文件,然后定义了一个线程函数helloFunction,它将在线程中执行。在main函数中,我们创建了一个std::thread对象t,并将helloFunction作为参数传递给它,这样就创建了一个新线程。t.join()调用会阻塞main函数,直到t所代表的线程执行完毕。
编译这个程序时,你需要链接线程支持库,可以使用-pthread选项:
g++ -pthread your_program.cpp -o your_program
如果你想要更高级的多线程功能,比如线程同步,你可以使用<mutex>、<condition_variable>、<future>、<atomic>等头文件中提供的工具。
例如,使用互斥锁(mutex)来保护共享资源:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 创建一个互斥锁
void print_block(int n, char c) {
mtx.lock(); // 加锁
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
mtx.unlock(); // 解锁
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
在这个例子中,我们使用std::mutex来确保两个线程不会同时打印到标准输出,这样可以避免输出的混乱。
请注意,多线程编程需要考虑线程安全问题,确保共享资源的正确访问,避免竞态条件和死锁等问题。