【发布时间】:2011-09-20 00:28:58
【问题描述】:
我有一个处理多个 TCP 连接的资源管理器。这些连接是 pthread。如何管理它以将数据从资源管理器发送到所有这些线程?甚至更好:如何确定我必须将这个命令发送到哪个线程?
例如:我有 2 个线程,一个使用 pid 3333,一个使用 pid 4444。用户发送一个任务来对板进行编程(它是管理 FPGA 板的资源管理器)。资源管理器从列表中选择一块板,该 pid 也保存在其中。然后程序命令应该用这个pid发送到线程,或者,我首先想到的,发送到所有线程,线程决定它们是否继续。协议如下:<pid>#<board-id>#<file>
我在 main.c 中打开 2 个管道(用于写入线程和读取线程)并将它们作为参数提供给监听线程 (forthread-struct)。
main.c
// open Pipes to SSL
int rmsslpipe[2];
int sslrmpipe[2];
if (pipe(rmsslpipe) == -1) {
writelog(LOGERROR, "main: could not create RM-SSL reading pipe");
exit(1);
}
if (pipe(sslrmpipe) == -1) {
writelog(LOGERROR, "main: could not create RM-SSL reading pipe");
exit(1);
}
int rmtosslserver = rmsslpipe[1];
int sslservertorm = sslrmpipe[0];
// start SSL-Server as a pthread
pthread_t thread;
forthread* ft = malloc(sizeof(forthread));
ft->rmtosslserver = rmsslpipe[0];
ft->sslservertorm = sslrmpipe[1];
pthread_mutex_t ftmutex;
pthread_mutex_init(&ftmutex, NULL);
ft->mutex = ftmutex;
pthread_create(&thread, NULL, startProgramserver, (void*) ft);
该线程现在侦听新连接,如果有新连接,它会创建一个新线程,并以forthread-struct 作为参数。这个线程是动作发生的地方:)
void* startProgramserver(void* ft) {
int sock, s;
forthread* f = (forthread*) ft;
// open TCP-Socket
sock = tcp_listen();
while(1){
if((s=accept(sock,0,0))<0) {
printf("Problem accepting");
// try again
sleep(60);
continue;
}
writelog(LOGNOTE, "New SSL-Connection accepted");
f->socket = s;
pthread_t thread;
pthread_create(&thread, NULL, serveClient, (void*) f);
}
exit(0);
}
这个线程现在初始化连接,从客户端获取一些信息,然后等待资源管理器获取新命令。
n=read(f->rmtosslserver, bufw, BUFSIZZ);
但是如果有不止一个线程,这将失败。那我该如何管理呢?
【问题讨论】:
标签: c multithreading pthreads pipe