在Ubuntu上进行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 << "Hello from the main thread!" << std::endl;
return 0;
}
在这个例子中,我们首先包含了<thread>
头文件。然后定义了一个简单的函数helloFunction
,它将在新线程中执行。在main
函数中,我们使用std::thread
创建了一个新线程,并将helloFunction
作为参数传递给它。最后,我们调用t.join()
等待线程完成执行。
要编译这个程序,你需要使用支持C++11的编译器,并且链接线程库。可以使用以下命令来编译:
g++ -std=c++11 -pthread your_program.cpp -o your_program
这里-std=c++11
告诉编译器使用C++11标准,而-pthread
是链接线程库的选项。
如果你想要在线程之间共享数据或者同步它们的执行,你可以使用<mutex>
、<condition_variable>
、<atomic>
等同步原语。
下面是一个使用互斥锁(std::mutex
)来保护共享资源的例子:
#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;
}
在这个例子中,我们定义了一个全局的std::mutex
对象mtx
,并在printMessage
函数中使用lock()
和unlock()
方法来确保每次只有一个线程可以访问std::cout
。
请注意,从C++17开始,推荐使用std::lock_guard
或std::unique_lock
来自动管理锁的生命周期,这样可以避免忘记解锁导致的死锁问题。下面是使用std::lock_guard
的例子:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void printMessage(const std::string& msg) {
std::lock_guard<std::mutex> lock(mtx); // 自动管理锁
std::cout << msg << std::endl;
}
int main() {
std::thread t1(printMessage, "Hello from thread 1!");
std::thread t2(printMessage, "Hello from thread 2!");
t1.join();
t2.join();
return 0;
}
在这个版本中,我们使用了std::lock_guard
,它在构造时锁定互斥锁,在析构时自动解锁,这样可以确保即使在函数执行过程中抛出异常,锁也会被正确释放。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Ubuntu C++多线程怎么实现