Linux C++多线程编程实例
多线程是指在一个程序中同时运行多个线程,每个线程执行不同的任务。在Linux环境下,C++多线程编程通常使用POSIX线程(pthread)库来实现。
以下是一个简单的Linux C++多线程示例,创建两个线程分别打印奇数和偶数:
#include <iostream>
#include <pthread.h>
using namespace std;
void* printOdd(void* arg) {
for (int i = 1; i <= 100; i += 2) {
cout << "Odd: "<< i << endl;
}
return NULL;
}
void* printEven(void* arg) {
for (int i = 2; i <= 100; i += 2) {
cout << "Even: "<< i << endl;
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
// 创建线程1
if (pthread_create(&thread1, NULL, printOdd, NULL) != 0) {
cerr << "Failed to create thread1" << endl;
return 1;
}
// 创建线程2
if (pthread_create(&thread2, NULL, printEven, NULL) != 0) {
cerr << "Failed to create thread2" << endl;
return 1;
}
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
cout << "Main thread exiting." << endl;
return 0;
}
使用g++编译并运行上述代码:
g++ -o multi_thread_example multi_thread_example.cpp -lpthread
./multi_thread_example
问题描述:多个线程同时访问共享资源可能导致数据不一致。
解决方法:使用互斥锁(mutex)或其他同步机制保护共享资源。
#include <mutex>
std::mutex mtx;
void safePrint(const std::string& msg) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << msg << std::endl;
}
问题描述:两个或多个线程互相等待对方释放资源,导致程序无法继续执行。
解决方法:确保锁的获取顺序一致,避免循环等待。
std::mutex mtx1, mtx2;
void threadFunc1() {
std::lock(mtx1, mtx2);
std::lock_guard<std::mutex> lock1(mtx1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(mtx2, std::adopt_lock);
// 访问共享资源
}
void threadFunc2() {
std::lock(mtx1, mtx2);
std::lock_guard<std::mutex> lock1(mtx1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(mtx2, std::adopt_lock);
// 访问共享资源
}
通过以上示例和解决方法,您可以更好地理解和应用Linux C++多线程编程。
领取专属 10元无门槛券
手把手带您无忧上云