這裏是C.螺紋服務器代碼我的問題是:我們需要設置未使用的線程爲NULL?在java中,我們需要將線程設置爲NULL以讓它返回到線程池。C中的多線程:我們是否需要將未使用的線程設置爲NULL?
我作出改變,以馬丁·布羅德赫斯特的源代碼(見灰色文本爲註釋)
/*
* A threaded server
* by Martin Broadhurst (www.martinbroadhurst.com)
* Compile with -pthread
*/
#include <stdio.h>
#include <string.h> /* memset() */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <pthread.h>
#define PORT "32001" /* Port to listen on */
#define BACKLOG 10 /* Passed to listen() */
void *handle(void *pnewsock)
{
/* send(), recv(), close() */
return NULL;
}
int main(void)
{
int sock;
pthread_t thread;
struct addrinfo hints, *res;
int reuseaddr = 1; /* True */
/* Get the address info */
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(NULL, PORT, &hints, &res) != 0) {
perror("getaddrinfo");
return 1;
}
/* Create the socket */
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock == -1) {
perror("socket");
return 1;
}
/* Enable the socket to reuse the address */
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1) {
perror("setsockopt");
return 1;
}
/* Bind to the address */
if (bind(sock, res->ai_addr, res->ai_addrlen) == -1) {
perror("bind");
return 0;
}
freeaddrinfo(res);
/* Listen */
if (listen(sock, BACKLOG) == -1) {
perror("listen");
return 0;
}
/* Main loop */
while (1) {
pthread_attr_t *attr; //<===I added this
size_t size = sizeof(struct sockaddr_in);
struct sockaddr_in their_addr;
int * ptr; //<===I added this
ptr = malloc(sizeof(int)); //<===I added this
ptr = accept(sock, (struct sockaddr*)&their_addr, &size);
if (newsock == -1) {
perror("accept");
}
else {
printf("Got a connection from %s on port %d\n",
inet_ntoa(their_addr.sin_addr), htons(their_addr.sin_port));
//I added the following "if" statement
if (pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED) != 0){
fprintf(stderr, "Failed to set thread detached\n");
}
else {
//if (pthread_create(&thread, NULL, handle, &newsock) != 0) {
if (pthread_create(&thread, attr, handle, ptr) != 0) {
fprintf(stderr, "Failed to create thread\n");
}
}
}
}
close(sock);
return 0;
}
========== - ============ == 代碼從這裏: http://martinbroadhurst.com/source/threaded-server.c.html
你說得對。 &newsock是危險的。不僅如此,它只是簡單的破碎。它需要修復,但對於這樣簡單的事情(例如newsock是int),我會(void *)newsock並讓線程執行int newsock =(long)ptr而不是去malloc。我只有malloc,如果有一個控制結構正在填充 –
@CraigEstey我推薦malloc,因爲我不知道是否能夠做到這一點是保證是可移植的 - 你有一個關於往返轉換的POSIX參考整數指針和返回? – Random832
即使對於使用LP32/LLP64型號的braindamaged MS編譯器,它也會一直有效。所有Unix系統都使用LP32/LP64。對於32位,這是沒有意義的。以下是參考/標準,在90年代正式推出http://www.unix.org/version2/whatsnew/lp64_wp.html它甚至可以用於LLP64,因爲我們只需要低32位。爲簡潔起見,我可以完成int newsock =(int)ptr;而且,我是一個參考,因爲我已經做了這麼多次30多年。你總是可以僞裝一個指針內的int - 查看錶格 –