簡體   English   中英

如何加入以正在運行的pthread數組結尾的pthread

[英]How to join pthread which ended from array of running pthread

我有一個用C ++編寫的聊天服務器,我對phtreads有問題。 該服務器應該處理多個連接,因此我創建了pthread數組。 當新的客戶端連接時,它將從數組中為該客戶端提供一個pthread,並在通訊已完成的地方調用handle函數。 但是,當此客戶端斷開連接時,我不知道如何查找哪個pthread結束以及哪個pthread數組索引為空。 我知道這段代碼很可怕,但是我真的想使這個程序更好

所以我的問題是我能這樣做嗎,當一個pthread結束時,我將為連接到潛在的下一個客戶端的那個pthread數組清空該索引,而當有更多人說100個人連接時,我將重新分配該數組?

我如何找到哪個pthread結尾於加入那個pthread並找到哪個索引現在可以再次自由使用?

struct parsing{
     int socket;
};

int i = 0;
int strop = 100;
pthread_t *thread;
thread = (pthread_t*)malloc(sizeof(pthread_t)*100);
struct parsing args;
while (1)
{
    if((client_sock = accept(socket_desc, (struct sockaddr *)&socket_addr, (socklen_t *)&client_sock_len)) < 0)
    {
        fprintf(stderr,"Accept Error");
        return 5;
    }
    printf("connected %d",client_sock);
    args.socket = client_sock;
    pthread_create(&thread[i], NULL, &handle_connection, (void *)&args);
    i++;
    if (i == strop)
    {
        strop = strop + 100;
        void * ptr = (pthread_t*)realloc(thread,sizeof(pthread_t)*strop);
    }
}   

我如何找到哪個pthread結尾於加入那個pthread並找到哪個索引現在可以再次自由使用?

pthreads API沒有提供發現終止線程的方法。 Glibc具有不可移植的擴展,通過它您可以嘗試對特定線程進行非阻塞連接(請參閱pthread_tryjoin_np() ),如果您可以使用它,則可以圍繞它構建基於輪詢的解決方案。

但是我想說,完成此任務的正確方法是為工作線程建立一種機制,以告知主線程它們已完成。 例如,他們可以將自己的線程ID添加到主線程也可以看到的鏈接列表中,然后發送信號或使用pthread_cond_signal()引起主線程的注意。 確保為多線程訪問共享變量提供正確的同步。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM