调用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 invokedn");
sleep(1); //avoid heavy prints 
}
}
void* thread_function2(void *arg)
{
while(1)
{
printf(" thread_function2 invokedn");
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, '', 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;
}

最新更新