0
我有一個結構數組和字段指針函數的結構數組。多線程函數調用
我現在正在做的是循環訪問數組並調用每個註冊函數。
我需要的是我的結構中的每個元素數組調用單獨的獨立線程中的註冊函數。
如果需要,我還可以發佈代碼示例。對不起,我的英語:)
郵政代碼:
#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;
}
你在做什麼有困難?開始線程,同步它們? – forsvarir 2011-03-30 19:25:21
請發帖。 – karlphillip 2011-03-30 19:25:22
按要求添加的代碼示例 – cheshie 2011-04-01 09:45:13