C:在不使用全局变量的情况下,从创建的线程中操作在 main 中声明的结构

标签 c linux variables pthreads structure

我正在尝试了解线程在应用程序中的使用(我知道我正在做的事情在某种意义上可能是愚蠢的)并且我正在尝试了解如何操作在 main 中的结构中声明的变量从创建的线程。到目前为止我有:

typedef struct Chi_Server {

    int thread_status;
    int active_connections;

    pthread_t thread_id;
    pthread_attr_t thread_attribute;
    struct thread_info *tinfo;

} CHI_SERVER;

int main(void) {

    CHI_SERVER *chi_server;

    chi_server_start_server(chi_server);

    if (pthread_create(&chi_server->thread_id, (void *) &chi_server->thread_attribute, &chi_server_runtime, &chi_server)) {

        perror("Creating main thread");

    }

    initscr();
    noecho();
    cbreak();
    nodelay(stdscr, TRUE);
    keypad(stdscr, TRUE);
    curs_set(0);

    do {

        chi_server_time_alive(chi_server);
        chi_server_display(chi_server);

    } while (getch() != 113);

    nocbreak();
    endwin();

    chi_server_stop_server(chi_server);

    return 0;

}

void *chi_server_runtime(void *chi_server) {

    chi_server->server_stats.active_connections = 1;

}

我刚刚创建了 = 1,这样我就可以查看是否可以在 main 中操作结构变量。到目前为止,我完全被难住了。有谁知道如何操作 main 中声明的结构?

最佳答案

您似乎对调用 pthread_create 时的引用感到困惑;您最后一个参数“&server”可能应该只是服务器。 您不能像在 server_runtime 中那样取消引用指向 void 的指针。 您应该将 struct Server 指针分配给 void 指针并使用它。

尝试使用 gcc -Wall thread.c -o thread -lpthread 进行编译

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct Server {
    pthread_attr_t thread_attribute;
    pthread_t thread_id;
    int active_connections;
};

void * server_runtime(void *);

/* Error checking omitted for clarity. */
int main()
{
    struct Server *server;
    void *result;

    server = malloc(sizeof(struct Server));
    pthread_attr_init(&server->thread_attribute);
    pthread_create(&server->thread_id, &server->thread_attribute, server_runtime, server);
    pthread_attr_destroy(&server->thread_attribute);
    pthread_join(server->thread_id, &result);
    printf("%d\n", server->active_connections);
    free(server);

    return 0;
}

void * server_runtime(void *p)
{
    struct Server *server = p;
    server->active_connections = 1;
    return NULL;
}

关于C:在不使用全局变量的情况下,从创建的线程中操作在 main 中声明的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17554427/

相关文章:

c - 取消引用空指针在 sizeof 操作中是否有效

java - 如何使用 Linux Shell 文件运行 TestNG

linux - C++ 服务器 - 超过 1024 个连接

c - 将字符串中的单个字符附加到 char 指针上

c++ - 什么是最好的自动完成/建议算法,数据结构 [C++/C]

c - C中的POSIX线程本地数据

c++ - 指向非指针变量结构的指针。这些变量,堆或堆栈在哪里?

variables - 在 zsh 中使用变量作为命令参数

javascript - linear-gradient() 值作为 js 变量

c - 将整个数组传递给函数