有这样的代码。有一个全局队列,在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;
}
例如--- ./main 3 3 并显示在屏幕上----- 16 16 16
我的线程是使用互斥锁进行同步的,为什么会这样?
答案 0 :(得分:2)
您不应该每次都致电srand()
。将呼叫转移到main
。否则,该值应该仅在秒边界上改变。