使用pthread实现多线程遇到小问题
多线程遍历三个string向量的实现分析与优化
先看看你目前写的代码片段(看起来还没写完):
#include<iostream> #include<pthread.h> #include<vector> #include<string> #include<fstream> using namespace std; int i_array1=-1,i_array2=0,i_array3=0; int total_array1,total_array2,total_array3; vector<string> array1; vector<string> array2; vector<string> array3; pthread_mutex_t count; void *dostuf(void *threadid) { string u... // 代码未完成部分 }
现有代码的几个问题
- 全用全局变量真的不是个好主意,不仅代码耦合得死死的,多线程下随便碰这些变量,很容易出现竞态条件,数据乱得你找不着北。
- 你定义了互斥锁
count,但没看到初始化和销毁的代码,默认初始化的锁可能根本起不了作用,线程同步等于白搭。 - 索引变量
i_array1这些的操作完全没加锁,多个线程同时改的话,索引值会乱跳,遍历肯定出错。 - 线程函数没写完,也没看到线程创建、等待回收的逻辑,完整的流程还没搭起来。
给你优化后的完整实现
我把参数封装成结构体,去掉了全局变量,同时把线程同步的逻辑补全了,你可以参考:
#include<iostream> #include<pthread.h> #include<vector> #include<string> #include<fstream> using namespace std; // 把线程需要的所有参数封装到结构体里,不用全局变量 struct ThreadData { vector<string>* targetVec; // 要遍历的向量指针 pthread_mutex_t* mutex; // 互斥锁指针,用于同步索引操作 int* currentIndex; // 当前遍历的索引 int totalSize; // 向量的总元素数 }; void *dostuf(void *arg) { // 把传入的参数转成结构体指针 ThreadData* data = static_cast<ThreadData*>(arg); while (true) { // 加锁!确保索引的修改是原子操作,避免多个线程抢着改 pthread_mutex_lock(data->mutex); int current = ++(*data->currentIndex); pthread_mutex_unlock(data->mutex); // 如果当前索引超过总元素数,说明遍历完了,退出线程 if (current >= data->totalSize) { break; } // 这里写你对每个元素的处理逻辑,我示例是打印出来 cout << "线程ID: " << pthread_self() << " 处理元素: " << (*data->targetVec)[current] << endl; } pthread_exit(nullptr); } int main() { // 先模拟填充三个向量的数据,你可以换成自己的数据源 vector<string> array1 = {"数组1元素1", "数组1元素2", "数组1元素3"}; vector<string> array2 = {"数组2元素1", "数组2元素2", "数组2元素3", "数组2元素4"}; vector<string> array3 = {"数组3元素1", "数组3元素2"}; // 每个向量的遍历起始索引,初始设为-1,这样第一次++后就是0 int idx1 = -1, idx2 = -1, idx3 = -1; pthread_mutex_t mutex; // 正确初始化互斥锁,attr传nullptr用默认属性 pthread_mutex_init(&mutex, nullptr); // 给每个线程准备好参数 ThreadData data1 = {&array1, &mutex, &idx1, array1.size()}; ThreadData data2 = {&array2, &mutex, &idx2, array2.size()}; ThreadData data3 = {&array3, &mutex, &idx3, array3.size()}; pthread_t thread1, thread2, thread3; // 创建三个线程,分别去遍历三个向量 pthread_create(&thread1, nullptr, dostuf, &data1); pthread_create(&thread2, nullptr, dostuf, &data2); pthread_create(&thread3, nullptr, dostuf, &data3); // 等待所有线程都跑完,再继续主程序 pthread_join(thread1, nullptr); pthread_join(thread2, nullptr); pthread_join(thread3, nullptr); // 用完锁记得销毁,避免资源泄漏 pthread_mutex_destroy(&mutex); return 0; }
优化点说明
- 用结构体传参,把每个线程需要的东西打包在一起,代码清爽多了,也不会因为全局变量互相干扰。
- 互斥锁的初始化和销毁都做了,保证线程同步的可靠性,索引修改的时候加锁,绝对不会出现多个线程同时改索引的问题。
- 每个线程独立处理自己的向量,逻辑清晰,遍历完成后自动退出,主程序等待所有线程结束再收尾。
内容的提问来源于stack exchange,提问作者criss
相关产品推荐
相关产品推荐

