c - 多线程函数调用

标签 c pthreads

我有一个结构体数组,其中包含数据字段和带有函数指针的字段。

我现在正在做的是循环遍历数组并调用每个注册的函数。

我需要的是在一个单独的独立线程中为结构数组中的每个元素调用注册函数。

如果需要,我也可以发布代码示例。抱歉我的英语:)

发布代码:

#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;
}

最佳答案

这是一个非常好的基本 pthreads 示例,应该可以帮助您继续: https://computing.llnl.gov/tutorials/pthreads/#CreatingThreads

基本上,您需要做的就是循环遍历函数指针数组并根据上述示例执行函数。

关于c - 多线程函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5491177/

相关文章:

c++ - 将 0 转换为 void

c - 如何根据C语言中的本地时间计算GMT时间

c - 编写文本编辑器时保存数据的好方法

c - 选择排序算法(C)

c++ - 如何在 C++ 中异步执行一个函数?

c - 如何删除C中字符串中的空格?

c++ - 当取消请求排队时,pthread_cancel() 将如何响应?

c - 在 C 中如何使 pthread 总共浪费 cpu 时间 1 秒?

php - 我如何在php多线程中使用静态方法

c++ - C++11中通过pthreads获取线程Core affinity