【问题标题】:Difference between vector and array in p_threads initialisationp_threads初始化中向量和数组的区别
【发布时间】:2020-05-28 15:36:11
【问题描述】:

我倾向于使用向量和智能指针而不是数组,因为这样更安全。问题是当初始化为数组时,我的线程成功加入主线程。但是,当初始化为向量时,情况并非如此。这是预期的,因为数组元素是通过引用访问的。

1.作为数组

pthread_t threads[numCPU]; // Initialised as an array

// Creating threads
for(long unsigned int i=0; i<numCPU; i++){
        rc = pthread_create(&threads[i], &attr, myfunc, (void *) args[i] );
        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Created Thread " + std::to_string(i)));
        }
}

// Joining thread
for(long unsigned int i=0; i<numCPU;i++){
      rc = pthread_join(threads[i], NULL);

        if (rc) {
            printUserMessage(std::string("Error; return code from pthread_create is : ") + std::to_string(rc));
        } else {
            printUserMessage(std::string("Joined Thread " + std::to_string(i)));
}

pthread_create 和 pthread_join 的签名将在以下情况下得到尊重:

std::vector<pthread_t *> threads(numCPU);

指针向量没有意义,我可能需要管理内存。有没有更安全的方法来创建线程?

【问题讨论】:

  • 有什么理由不使用std::thread
  • 这确实不能回答问题。这个答案已经有 8 年历史了,std::thread 在今天非常普遍。
  • @NathanOliver 不是 std::thread 最终编译为 posix 线程的 c++ API 吗?我需要对线程和互斥锁进行更多控制。这就是我仍在使用 pthreads 的原因。
  • 是的,但它是 RAII 并且更容易使用(恕我直言)。您实际上可以使用类型系统并摆脱所有与void*'s 之间的转换。

标签: c++ arrays pthreads stdvector


【解决方案1】:

我倾向于使用向量和智能指针而不是数组,因为这样更安全。

向量和智能指针并不比数组安全。

如果您希望在运行时确定线程数,而没有恒定的上限,则使用向量而不是数组会很有用。否则就没用了。

不清楚为什么要创建指针向量。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多