![](/img/trans.png)
[英]How to get the operations to work without the use of global variables in C
[英]C: Manipulate a structure declaired in the main from a created thread without the use of global variables
我試圖理解應用程序中線程的使用(我知道我在做什么在某種意義上可能是愚蠢的)我試圖理解如何操縱在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的指針。 您應該為void指針分配一個struct Server指針並使用它。
嘗試使用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;
}
在void * server_runtime(void * server)中。 你必須告訴*服務器是什么類型的。
我還沒有看到你的服務器聲明,但我想它看起來像這樣
int main()
{
struct yourstruct server;
if (pthread_create(&server->thread_id, (void *) &server->thread_attribute,
&server_runtime, &server))
{
perror("Creating main thread");
}
}
void *server_runtime(void *_server)
{
struct yourstruct *server = _server;
server->active_connections = 1;
}
可能像往常一樣錯過了一些東西。 祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.