#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
int randint(int sec,int num) {
srand(time(0)); // 使用当前时间作为随机数生成器的种子
int random_number = rand() % sec;
return random_number;
}
//pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
void* myFunction(void* arg) {
int param = *(int*)arg;
int count = 6;
int i;
for(i=0;i<count;i++){
printf(" thread %d! i = %d\n",param,i);
sleep(randint(5, param));
}
return NULL;
}
//gcc pthread.c -lpthread
int main() {
pthread_t myThread;
int param = 42;
if(pthread_create(&myThread, NULL, myFunction, ¶m) != 0) {
printf("Failed to create thread\n");
return 1;
}
sleep(3);
int th = 43;
pthread_t myThread2;
if(pthread_create(&myThread2, NULL, myFunction, &th) != 0) {
printf("Failed to create thread\n");
return 1;
}
// 等待新线程执行结束
pthread_join(myThread, NULL);
pthread_join(myThread2, NULL);
printf("Main thread exiting\n");
return 0;
}
xt@qisan:/opt/wks/cwks/alg02$ gcc pthread.c -lpthread
xt@qisan:/opt/wks/cwks/alg02$ ./a.out
thread 42! i = 0
thread 42! i = 1
thread 42! i = 2
thread 43! i = 0
thread 42! i = 3
thread 43! i = 1
thread 43! i = 2
thread 42! i = 4
thread 43! i = 3
thread 42! i = 5
thread 43! i = 4
thread 43! i = 5
Main thread exiting
xt@qisan:/opt/wks/cwks/alg02$ ./a.out
thread 42! i = 0
thread 43! i = 0
thread 42! i = 1
thread 43! i = 1
thread 43! i = 2
thread 43! i = 3
thread 43! i = 4
thread 43! i = 5
thread 42! i = 2
thread 42! i = 3
thread 42! i = 4
thread 42! i = 5
Main thread exiting
一文搞定之C语言多线程
|