編譯的時候還要下-pthread指令
ex:gcc test.c -o test -pthread
pthread_create(pid,NULL,*void,(*void)arg);
第三項是pthread要跑的function位置,這個function只能接受一個argument傳入,限定為void type,有需求傳入多個arguments時,定一個struct把需要的arguments都包起來。可以回傳值,所以也限定為void*,因此function定義時要定成void* mydeffunc(void* arg)
ex:
void *doit(void *arg);
/*define a struct to wrap needed arguments*/
struct myDefStruct
{
struct sockaddr_in servaddr;
int sockfd;
};
/*call pthread_create的時候*/
/*when call pthread_create*/
struct myDefStruct *myDefPtr;
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (__SOCKADDR_ARG) &cliaddr, &clilen);
myDefPtr= (struct myDefStruct*)malloc(sizeof(struct myDefStruct));
myDefPtr->servaddr = cliaddr;
myDefPtr->sockfd = connfd;
pthread_create(&tid, NULL, &doit, (void*)myDefPtr);
}
/*如何取出void*型別的資訊*/
/*How to retrieve the data in void* type by casting*/
void *doit(void *arg)
{
int sockfd = ((struct myDefStruct*)arg)->sockfd;
struct sockaddr_in servaddr = ((struct myDefStruct*)arg)->servaddr;
...............
}
沒有留言:
張貼留言