从 pthread

编程入门 行业动态 更新时间:2024-10-28 09:22:00
本文介绍了从 pthread_create 向线程函数传递多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我第一次尝试在 C 中进行线程处理.我正在创建一个循环有界缓冲区.我知道如何创建线程,但我见过的所有示例都只有接受一个 void 参数的线程函数,但不幸的是,我的工人规范要求我使用三个,如下所示:

this is my first attempt at threading in C. I am creating a circularly bounded buffer. I know how to create the thread, but all examples I have seen only have threaded functions that accept one void parameter, but unfortunately my worker's specification requires me to use three, as shown here:

void bufferRead(BoundedBuffer* buffer, char* data, int count) { pthread_mutex_lock(&buffer->mutexBuffer); <snip> pthread_mutex_unlock(&buffer->mutexBuffer); }

这是我的 pthread_create 语句

Here is my pthread_create statement

pthread_create(&buffer.readThread, NULL, (void *)bufferRead, &readParams)

还有我的 readParams 结构/赋值

And my readParams struct/assignments

struct readThreadParams { BoundedBuffer b; char* data; int count; }; struct readThreadParams readParams; readParams.b = buffer2; readParams.data = out_array; readParams.count = in_size;

任何关于在传递给 bufferRead 函数后如何分配结构的每个参数的建议将不胜感激.

Any advice on how to assign each of the struct's parameters after passing to the bufferRead function would be greatly appreciated.

推荐答案

那是因为您实际上只需要一个参数.当我们有多个值时,通常情况下,我们将其封装到一个结构中.pthread_create 将调用的函数类型是不可协商的.这是一个类型转换你的函数指针可能会给你带来严重麻烦的地方.

That's because you only really need one parameter. When we have more than one value, as is typically the case, we encapsulate that into a struct. The function type that pthread_create will call is non-negotiable. This is an area where type-casting your function pointer can get you into serious trouble.

#include <pthread.h> #include <stdlib.h> struct BoundedBuffer { pthread_t readThread; pthread_mutex_t mutexBuffer; } buffer2; struct readThreadParams { struct BoundedBuffer b; char* data; int count; }; void *bufferRead (void *context) { struct readThreadParams *readParams = context; pthread_mutex_lock(&readParams->b.mutexBuffer); //<snip> pthread_mutex_unlock(&readParams->b.mutexBuffer); return NULL; } int main(void) { int ret; char *out_array = malloc(42); size_t in_size = 42; struct readThreadParams readParams; readParams.b = buffer2; readParams.data = out_array; readParams.count = in_size; /* I presume that by "buffer", you really meant the .b member of * struct readThreadParams. Further, this must have a member * named readThread of type pthread_t, etc. */ ret = pthread_create(&readParams.b.readThread, NULL, bufferRead, &readParams); if (!ret) { pthread_join(&readParams.b.readThread, NULL); } free(out_array); return ret; }

更多推荐

从 pthread

本文发布于:2023-10-09 02:07:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:pthread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!