【发布时间】:2014-06-27 21:14:05
【问题描述】:
到目前为止,我终于可以为我正在制作的一些测试应用程序创建一个准确的消费者-生产者类型模型,但最后一点给我带来了一些问题。
我为我的应用程序设置了 2 个结构。一个用于链接列表,用作必须完成的工作列表。另一个是特定于每个线程的结构,其中包含指向链表的双指针。我不使用单个指针,因为我无法在一个线程中修改指针并检测另一个线程的变化。
//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_specs 中的双指针被绑定到 list_of_work 结构的根的双指针,如下所示:
主要:
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 次强制转换,1 次强制强制转换 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_of_work *get_work(list_of_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_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’
感谢能帮助我的人!
【问题讨论】:
-
thread->drives:没有这样的成员。也许发布真实代码会有所帮助。 -
啊,这是真正的代码。我只是更改了一些引用以使我的意图更清晰
-
演员阵容也不正确(而且它的表面必要性应该是一个不正确的危险信号)。
list_of_work *work_list = (list_of_work *)thread->linked_list;应该是list_of_work *work_list = *(thread->linked_list);,但老实说,如果你想共享和互斥控制单个链表头指针,这不是这样做的方法。 -
这是我第一次使用 pthread 和链表...您建议我如何共享单个链表?唯一不那么复杂的方法是在全球范围内分享它,但我真的不喜欢这样做
-
不用担心。我认为this 是你想要做的,但我可能有点过于简单化了。当您在线程细读列表时有活动的插入器时会变得更加困难,但是对于更简单的多线程枚举,您只需要一个互斥锁。甚至没有正确的原子内在函数。
标签: c pointers struct linked-list double-pointer