[英]C - Pthreads Using a Controller Function
我试图在main()
之外编写一个玩具pthread控制器函数。
将参数struct传递到pthread_create
函数时遇到问题。 本质上,它什么也不输出(我们称其为“无”)。
我假设我在pthread_create
指向struct wr
的指针做错了什么,而不是输出结构,而是尝试输出结构指针。 我在这里做错了什么?
我在网上看到的每个示例在main()
都有pthread实现,这仅仅是“简单”说明的副产品,还是这首先应该是怎么做的?
注意:是的,我的确意识到两个线程池是同步启动的。 这不是这里的问题。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct wr {
char str[100];
int count;
};
void writeline (struct wr writer) {
printf("out: %s\n", writer.str);
writer.count--; //this is left over, just ignore it for now.
pthread_exit(0);
return NULL;
}
void controller (void (*func)(struct wr), struct wr writer, int threads){
pthread_t *tid;
tid = malloc(sizeof(pthread_t) * threads);
int i;
for (i = threads; i > 0; i--){
// Right here is where the problem starts.
pthread_create(&tid[i], NULL, (void *) writeline, (void *) &writer);
}
for (i = threads; i > 0; i--) {
pthread_join(tid[i], NULL);
}
}
int main () {
struct wr writer1 = {.str = "Bop!", .count = 3};
struct wr writer2 = {.str = "Boop!", .count = 3};
controller(writeline, writer1, 10);
controller(writeline, writer2, 2);
return 0;
}
和我的Makefile选项:
CC=gcc
CFLAGS=-g -Wall -pthread
1)您对该函数的转换是错误的:
pthread_create(&tid[i], NULL, (void *) writeline, (void *) &writer);
您正在将函数指针转换为数据指针,这毫无意义。
2)您为tid
编制索引也是错误的。 例如,当您分配2个pthread_t
元素时,有效索引为0和1。但是您的for循环访问为1和2。
3)您没有使用函数指针。 因此,您根本不需要通过它。
4)线程函数将void *
作为参数,而不是struct
。 因此,您需要对其进行更改,并通过将其强制转换回struct wr*
来检索函数中的参数。
具有以上更改的代码:
5)您需要pthread_exit
或return
。 pthread_exit
不返回。 删除其中之一。
void* writeline (void *arg) {
struct wr writer = *(struct wr*)arg;
printf("out: %s\n", writer.str);
return NULL;
}
void controller (struct wr writer, int threads){
pthread_t *tid;
tid = malloc(sizeof(pthread_t) * threads);
int i;
for (i = 0; i <threads; i++) {
pthread_create(&tid[i], NULL, writeline, &writer);
}
for (i = 0; i <threads; i++) {
pthread_join(tid[i], NULL);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.