为什么队列的所有元素都是一样的,元素被添加到 posix 线程中的队列中
Why all the elements of the queue are the same, elements are added to the queue in the posix thread
有这样的代码。有一个全局队列,在 posix 线程中您添加新元素,但是当添加所有元素后,我打印到屏幕队列时,结果发现所有元素都相同
#include <fstream>
#include <iostream>
#include <pthread.h>
#include <queue>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <cassert>
std::queue<int> q;
pthread_mutex_t set_queue_mutex;
void* producer(void*)
{
srand(time(NULL));
size_t m = rand() % 100 + 1;
usleep(m/1000);
size_t n = rand() % 100 + 1;
int s = q.size();
pthread_mutex_lock(&set_queue_mutex);
q.push(n);
pthread_mutex_unlock(&set_queue_mutex);
}
int main(int c, char** v)
{
int n = 0;
int m = 0;
///* Usage */
if(c == 3)
{
n = atoi(v[1]);
m = atoi(v[2]);
}
else
{
std::cout << "Wrong count of parameters, see usage: test $1 $2" << std::endl;
exit(0);
}
pthread_t* t1 = new pthread_t[n];
assert(t1 != 0);
pthread_t* t2 = new pthread_t[m];
assert(t2 != 0);
for(int i = 0; i < n; ++i)
{
pthread_create(&t1[i], 0, &producer, 0);
pthread_join(t1[i], 0);
}
while(q.size() != 0)
{
std::cout << q.front() << std::endl;
q.pop();
}
return 0;
}
例如--- ./主 3 3并显示在屏幕上 ----- 16 16 16
我的线程使用互斥锁同步,为什么?
你不应该每次都打电话给srand()
。将呼叫移至main
。否则,该值应该只在秒边界上更改。
相关文章:
- 使用 <list> (错误 C2760) 打印队列的元素
- 从队列中删除第一个元素C++
- 如何在 c++ 中创建对的优先级队列.这会弹出具有最小值的元素.默认的弹出最大值
- 如何将元素从 STL 队列传递到函数?
- 如何实现唯一 id 队列,其中元素可以在 C++ 中"bumped"到顶部?
- 我们可以在队列前面以 O(1) 时间复杂度排队一个元素吗?
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- 将元素从队列复制到堆栈
- 如何删除在没有STL的队列中存储在数组中的第一个字符串元素
- 打印队列元素的队列
- 如何获得向量队列的前部或顶部元素
- 从队列中编辑元素而不将其删除
- 在队列中,插入和删除后,被删除的元素也会出现在输出中.为什么
- 为具有可变元素(C++)的优先级队列确定最佳ADT
- 正在提取优先级队列的最后一个元素
- 当我插入元素时,C 优先级队列会崩溃
- 在队列中插入向量元素
- 我如何在队列中排序元素
- 将添加到队列的第一个元素作为 null 进行排序