在Linux中使用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作为参数传递给它。最后,我们使用join()方法等待线程完成。
要编译这个程序,你需要使用支持C++11的编译器,如g++。在命令行中,你可以使用以下命令编译和运行程序:
g++ -std=c++11 -pthread your_file_name.cpp -o your_output_file_name
./your_output_file_name
注意:在编译时添加-pthread选项,以便正确链接线程库。
如果你需要在多个线程之间共享数据,可以使用std::mutex、std::lock_guard等同步原语来确保线程安全。这是一个简单的生产者-消费者示例:
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
std::queue<int> dataQueue;
std::mutex mtx;
std::condition_variable cv;
bool done = false;
// 生产者线程函数
void producer() {
for (int i = 0; i < 5; ++i) {
std::unique_lock<std::mutex> lock(mtx);
dataQueue.push(i);
std::cout << "Produced: "<< i << std::endl;
lock.unlock();
cv.notify_one();
}
done = true;
}
// 消费者线程函数
void consumer() {
while (!done) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return !dataQueue.empty() || done; });
if (!dataQueue.empty()) {
int value = dataQueue.front();
dataQueue.pop();
std::cout << "Consumed: " << value << std::endl;
}
}
}
int main() {
std::thread producerThread(producer);
std::thread consumerThread(consumer);
producerThread.join();
consumerThread.join();
return 0;
}
在这个例子中,我们使用了std::mutex来保护对共享队列的访问,以及std::condition_variable来同步生产者和消费者线程。