我有一个结构数组,其中包含数据和字段,以及指向函数的指针。
我现在正在做的是循环访问数组并调用每个注册的函数。
我需要的是我的结构数组中的每个元素在一个单独的独立线程中调用注册函数。
如果需要,我也可以发布代码示例。抱歉我的英文:)
发布代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define NTHREAD 3
struct server_t {
char *name;
int (*triggered)(struct server_t *);
};
typedef struct server_t server_t;
int triggered1(struct server_t * server)
{
if (time(NULL) % 1 == 0) {
printf("%s\n", __FUNCTION__);
pthread_exit(0);
return 0;
} else {
return -1;
}
}
int triggered2(struct server_t * server)
{
if (time(NULL) % 2 == 0) {
printf("%s\n", __FUNCTION__);
pthread_exit(0);
return 0;
} else {
return -1;
}
}
int triggered3(struct server_t * server)
{
if (time(NULL) % 5 == 0) {
printf("%s\n", __FUNCTION__);
pthread_exit(0);
return 0;
} else {
return -1;
}
}
int main()
{
pthread_t threads[NTHREAD];
int iret[NTHREAD]; int i = 0;
server_t servers[] = {
{"server1", triggered1},
{"server2", triggered2},
{"server3", triggered3},
};
/*
So, i have an array of structures. AND i have a main loop.
i want to create thread for each element of array, pass
structure's "triggered" function as start routine for it.
AND i need this start routine to periodically check for something.
So below some kind of an em.. code, that supposed to be.
*/
<create_threads(&servers);> // this function must create thread for each element of array
//with structure's "triggered" function as a start routine
//argument
/* after what threads are running and checking what they needed in an infinite loop. */
// ?maybe some code here?
return 0;
}
答案 0 :(得分:1)
这是一个非常好的,基本的pthreads示例,它可以让你前进: https://computing.llnl.gov/tutorials/pthreads/#CreatingThreads
基本上你需要做的就是遍历你的函数指针数组并根据上述例子执行函数。