簡體   English   中英

C中調用線程創建函數

[英]Calling thread create function in C

如果我在 main 的無限 while 循環中使用 pthread_create() 調用,它是每次創建多個線程還是只創建我需要的 2 個線程?

while(1){ 
   pthread_create(&thread_1...);
   pthread_create(&thread_2...);
}

它每次創建多個線程。

您可以使用pthread_cancel取消進程中的任何線程。

以下是在某些事件/超時等情況下處理線程終止的多種方法之一。

#include <stdio.h>
#include <signal.h> // for sigaction
#include <stdlib.h> // for exit and 
#include <pthread.h> // for pthread
#include <string.h> // for memset
    
#define TIMEOUT 10


pthread_t tid1, tid2;

void* thread_function1(void *arg)
{
    while(1) 
    {
        printf(" thread_function1 invoked\n");
        sleep(1); //avoid heavy prints 
    }
}

void* thread_function2(void *arg)
{
    while(1)
    {
        printf(" thread_function2 invoked\n");
        sleep(1); //avoid heavy prints
    }
}   

static void timer_handler(int sig, siginfo_t *siginfo, void *context)
{
    printf("Inside handler function timeout happened \n");
    if( sig == SIGALRM)
    {
        pthread_cancel(tid1);
        pthread_cancel(tid2);
        //exit(0); to exit from main
    }
}

int main()
{
    int count = 0;
    void *status;
    
    struct sigaction act;
    memset (&act, '\0', sizeof(act));
    sigemptyset(&act.sa_mask);
    /* Use the sa_sigaction field because the handles has two additional parameters */
    act.sa_sigaction = timer_handler;
    /* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler. */
    act.sa_flags = SA_SIGINFO;
    if (sigaction(SIGALRM, &act, NULL) < 0)
    {
        perror ("sigaction SIGALRM");
        return 1;
    }
    alarm (TIMEOUT);
    pthread_create(&tid1,NULL,thread_function1,NULL);
    pthread_create(&tid2,NULL,thread_function2,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    printf(" MIAN ENDS ...BYE BYE \n");
    return 0;
}

暫無
暫無

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

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