【问题标题】:Sharing a list between threads in C++ [closed]在 C++ 中的线程之间共享列表 [关闭]
【发布时间】:2019-05-22 20:00:47
【问题描述】:

我在 C++ 的 2 个或更多线程之间共享列表时遇到问题。我在 main() 中初始化我的列表,然后创建线程,将列表对象指针作为参数传递:

pthread_create(&(tid[i]), NULL, &threadfunction, &l);

&l 是参数。这是从 2 个或更多线程操作同一列表的正确方法吗?我使用一个简单的互斥锁来锁定/解锁,因此一次访问它的线程不超过一个。

编辑:下面的代码


#include <stdio.h> 
#include <string.h> 
#include <pthread.h> 
#include <stdlib.h> 
#include <unistd.h>
#include "list.h" 

using namespace std;
int count = 0;
pthread_t tid[2]; 
pthread_mutex_t lock; 

void* trythis(void *arg) 
{ 
    pthread_mutex_lock(&lock); 
    printf("Starting thread\n");
    count++;
    printf("%d\n", count);
    if(count == 1)
    {
        ((list *)arg)->Append((char *)"some", (char *)"thing");
        printf("Appending done\n");
    }
    else
    {
        ((list *)arg)->Append((char *)"some", (char *)"else");
        printf("Appending done\n");
    }

    pthread_mutex_unlock(&lock); 

    return NULL; 
} 

int main(void) 
{ 
    list* l = new list();
    int i = 0; 
    printf("Starting\n");
    if (pthread_mutex_init(&lock, NULL) != 0) 
    { 
        printf("mutex init has failed\n"); 
        return 1; 
    } 

while(i < 2) 
{ 
    int err = pthread_create(&(tid[i]), NULL, &trythis, &l); 
    if (err != 0) 
        printf("\nThread can't be created :[%s]", strerror(err)); 
    i++; 
} 

pthread_join(tid[0], NULL); 
printf("Im out 1\n");
pthread_join(tid[1], NULL); 
printf("Im out 2\n");

pthread_mutex_destroy(&lock); 

delete l;
return 0; 

}


Append() 函数只是在列表中添加一些元素(每个列表节点都有 2 个 char* 成员)。

【问题讨论】:

  • 一定要使用pthread吗? C++11+ 带有内置的线程支持,它是类型安全的,可以让你摆脱 pthread 使用的所有类型转换和 void*
  • 是的,我不得不遗憾地使用 pthread
  • 显示代码的其他部分。只要列表没有超出范围就可以了。
  • 这将创建线程,但要告诉您同步是否正确,我们需要查看同步代码。
  • @FraPapas on Linux std::thread 使用 pthread,所以从技术上讲,您正在使用它。作业要求?

标签: c++ linux multithreading


【解决方案1】:

在:

thread_create(&(tid[i]), NULL, &trythis, &l); 

它传递list* 类型的局部变量l 的地址,因此trythis 函数得到list** 并错误地将其转换为list*

改为按值传递l

thread_create(&(tid[i]), NULL, &trythis, l); 

【讨论】:

  • @FraPapas 或者,在堆栈list l; 上分配l 并删除delete l;
【解决方案2】:

也许要确保您传入的数据在线程的整个生命周期内都是有效的?如果它在线程完成使用它之前被销毁,那将导致未定义的行为。

pthread_create 的最后一个参数只是为了方便您重新使用具有不同参数的相同 start_routine。线程可以通过引用相同的变量来共享数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2017-11-30
    • 2015-11-19
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2012-07-06
    相关资源
    最近更新 更多