PracticeDev/study_clang/multthread/test.c

29 lines
796 B
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define NUM_THREADS 5 //线程个数
void *say_hello(void *args)
{
printf("Hello Runoob\n");
sleep(2);
}
int main()
{
//定义线程的 id 变量,多个变量使用数组
pthread_t tids[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
sleep(2);
//参数依次是创建的线程id线程参数调用的函数传入的函数参数
int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
if (ret != 0) {
printf("pthread_create error: error_code = %d\n", ret);
}
}
//等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
pthread_exit(NULL);
}
//g++ test.cpp -lpthread -o test