在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对象t,并将helloFunction作为参数传递给它。然后我们调用t.join()来等待线程完成其工作。
要编译这个程序,你需要使用支持C++11或更高版本的编译器,并且需要链接线程库。可以使用以下命令来编译:
g++ -std=c++11 -pthread your_program.cpp -o your_program
-pthread选项告诉编译器我们需要链接线程库。
如果你需要更多的控制,比如传递参数给线程函数或者在线程之间共享数据,<thread>头文件提供了多种成员函数和同步机制,例如std::mutex、std::lock_guard、std::condition_variable等。
下面是一个稍微复杂一点的例子,展示了如何在线程之间共享数据并使用互斥锁来避免竞争条件:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 创建一个互斥锁
// 线程函数
void increment(int& sharedValue) {
    mtx.lock(); // 锁定互斥锁
    ++sharedValue; // 修改共享值
    mtx.unlock(); // 解锁互斥锁
}
int main() {
    int sharedValue = 0;
    // 创建两个线程
    std::thread t1(increment, std::ref(sharedValue));
    std::thread t2(increment, std::ref(sharedValue));
    // 等待线程完成
    t1.join();
    t2.join();
    std::cout << "Shared value: " << sharedValue << std::endl;
    return 0;
}
在这个例子中,我们使用了std::ref来传递共享变量的引用给线程函数,并且使用了std::mutex来确保每次只有一个线程可以修改sharedValue。
编译和运行这个程序的方法与前面的例子相同。