为什么队列的所有元素都是一样的,元素被添加到 posix 线程中的队列中

Why all the elements of the queue are the same, elements are added to the queue in the posix thread

本文关键字:元素 队列 添加 posix 线程 一样 为什么      更新时间:2023-10-16

有这样的代码。有一个全局队列,在 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。否则,该值应该只在秒边界上更改。