在Ubuntu上使用C++实现多线程,你可以使用C++11标准库中的<thread>
头文件。下面是一个简单的例子,展示了如何在C++中创建和使用线程。
首先,确保你的编译器支持C++11或更高版本。你可以通过在编译命令中添加-std=c++11
(或更高版本,如-std=c++17
)来启用C++11特性。
以下是一个简单的多线程示例:
#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 thread!" << std::endl;
return 0;
}
将上述代码保存到文件multithreading_example.cpp
中,然后使用以下命令编译:
g++ -std=c++11 multithreading_example.cpp -o multithreading_example
运行编译后的程序:
./multithreading_example
你应该会看到两个输出,表明主线程和子线程都在运行。
如果你需要在线程之间传递数据,可以使用std::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;
}
在这个例子中,两个线程th1
和th2
都试图打印字符到标准输出。为了避免输出的混乱,我们使用了一个互斥锁mtx
来确保同一时间只有一个线程可以访问打印代码。
编译并运行这个程序,你会看到两个线程交替打印字符,而不会出现输出的混乱。
请注意,多线程编程可能会引入复杂的同步问题,因此在设计多线程应用程序时需要仔细考虑线程间的交互和数据共享。