我正在尝试了解线程在应用程序中的使用(我知道我正在做的事情在某种意义上可能是愚蠢的)并且我正在尝试了解如何操作在 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/