C pthread,带有双指针的链表
到目前为止,我终于为我正在制作的一些测试应用程序创建了一个精确的消费者-生产者类型模型,但最后一点给我带来了一些问题 我为我的应用程序设置了2个结构。一个用于链接列表,该列表用作必须完成的工作列表。另一个是特定于每个线程的结构,其中包含指向链接列表的双指针。我不使用单个指针,因为这样我就无法在一个线程中修改指针,并检测到另一个线程中的更改C pthread,带有双指针的链表,c,pointers,struct,linked-list,double-pointer,C,Pointers,Struct,Linked List,Double Pointer,到目前为止,我终于为我正在制作的一些测试应用程序创建了一个精确的消费者-生产者类型模型,但最后一点给我带来了一些问题 我为我的应用程序设置了2个结构。一个用于链接列表,该列表用作必须完成的工作列表。另一个是特定于每个线程的结构,其中包含指向链接列表的双指针。我不使用单个指针,因为这样我就无法在一个线程中修改指针,并检测到另一个线程中的更改 //linked list struct: typedef struct list_of_work list_of_work; struct list_of
//linked list struct:
typedef struct list_of_work list_of_work;
struct list_of_work {
// information for the work
list_of_work *next;
};
//thread struct:
typedef struct thread_specs {
list_of_work **linked_list;
unsigned short thread_id;
pthread_mutex_t *linked_list_mtx;
} thread_specs;
thread\u specs
中的双指针绑定到工作列表的根的双指针,如下所示:
大体上:
list_of_work *root;
list_of_work *traveller;
pthread_t thread1;
thread_specs thread1_info;
// allocating root and some other stuff
traveller = root;
thread1_info.linked_list = &traveller;
这一切都可以在没有警告或错误的情况下工作
现在,我继续使用以下工具创建pthread:
pthread_create(&thread1, NULL, worker, &thread1_info )
在我的pthread中,我执行了2次转换,一次转换thread_info结构,另一次转换链表。ptr是我的论点:
thread_specs *thread = (thread_specs *)ptr;
list_of_work *work_list = (list_of_work *)thread->linked_list;
list_of_work *temp;
这不会出错
然后我有一个名为list\u of u work*get\u work(list\u of u work*ptr)
的函数,该函数可以工作,因此我不会发布整个内容,但正如您所看到的,它希望看到指向链接列表的指针,并返回同一链接列表的指针(要么是NULL
,要么是下一个工作)
所以我使用这个函数来获得下一个工作,如下所示:
temp = get_work(*work_list);
if (temp != NULL) {
work_list = &temp;
printf("thread: %d || found work, printing type of work.... ",thread->thread_id);
}
现在这是关键。如何正确地将指针强制转换并传递到我的get\u work()
函数的第一个指针后面,以便它可以执行它所执行的操作
我的编译器发出警告:
recode.c:348:9: error: incompatible type for argument 1 of ‘get_work’
recode.c:169:14: note: expected ‘struct list_of_work *’ but argument is of type ‘list_of_work’
我感谢任何能帮助我的人 根据您发布的函数get_work()
的定义和错误消息,此问题如下:
temp = get_work(work_list);
^
/* Notice there's no dereferencing here */
函数需要一个指向struct list\u of \u work
的指针,而您需要传递struct list\u of \u work
线程->驱动器:没有这样的成员。也许发布真实的代码会有帮助。啊,这是真实的代码。我只是更改了一些参考资料,以使我的意图更加清晰。演员阵容也是不正确的(其表面上的必要性应该是它不正确的危险信号)<代码>工作列表*工作列表=(工作列表*)线程->链接列表代码>应该是工作列表*工作列表=*(线程->链接列表)代码>,但老实说,如果您试图共享和互斥控制单个链表头指针,这不是实现此操作的方法。这是我第一次使用pthread和链表。。。您建议我如何共享一个链接列表?唯一不那么复杂的方式是在全球范围内分享,但我真的不喜欢这样做,不用担心。我想这就是你想要做的,但我可能把事情简单化了很多。当线程仔细阅读列表时,如果有活动的插入器,这会变得更加困难,但对于更简单的多线程枚举,只需要一个互斥就可以了。即使是正确的原子本质也不行。