0

有这样的代码。有一个全局队列,并且在 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

我的线程是使用互斥锁同步的,为什么?

4

1 回答 1

2

你不应该srand()每次都打电话。将呼叫移至main。否则,该值应该仅在秒边界上更改。

于 2013-10-29T09:32:31.923 回答