当前位置: 代码迷 >> 综合 >> 多线程的一种开启方法
  详细解决方案

多线程的一种开启方法

热度:52   发布时间:2024-02-24 04:57:56.0
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>#define THREAD_CNT  3     //线程个数void *thread_1(void *arg)
{while (1){printf("线程1启动\n");sleep(2);}pthread_exit(NULL);
}void *thread_2(void *arg)
{while (1){printf("线程2启动\n");sleep(2);}pthread_exit(NULL);
}void *thread_3(void *arg)
{while (1){printf("线程3启动\n");sleep(2);}pthread_exit(NULL);
}typedef void * (*ThreadFun)(void *);pthread_t threadHandle[THREAD_CNT];
ThreadFun threads[THREAD_CNT] = {thread_1, thread_2, thread_3};void InitThreads()
{int i;for (i = 0; i < THREAD_CNT; i++){int ret = pthread_create(&threadHandle[i], NULL ,threads[i], NULL);if(ret < 0){printf("线程%d开启失败!\n", i);return;}}
}int main()
{InitThreads();pthread_exit(NULL);
}

 

  相关解决方案