介绍Linux下多线程编程的博客:https://www.cnblogs.com/nfcm/p/7653433.html
pthread_create传递带参数的函数:https://blog.csdn.net/computerme/article/details/52421928
结合这些知识,自己写了了一个demo,其中实现了多线程、传递参数与利用锁进行同步。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#define thread_num 8
int num=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct String{
char c[20];
int len;
} Str;
void * func_thread(void * arg)
{
Str * para=(Str *)arg;
pthread_mutex_lock(&mutex);
while(num<20){
printf("this is func_%s,%d!\n",para->c,para->len);
num++;
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex);
}
pthread_mutex_unlock(&mutex);
}
int func()
{
pthread_t pid[thread_num];
void * ps[thread_num];
Str arg[8]={{"zero",4},{"one",3},{"two",3},{"three",5},{"four",4},
{"five",4},{"six",3},{"seven",5}};
int i;
for(i=0;i<thread_num;i++)
if(pthread_create(pid+i, NULL, func_thread,arg+i))
return -1;
for(i=0;i<thread_num;i++)
pthread_join(pid[i],ps+i);
printf("%d\n",num);
return 0;
}
int main()
{
func();
return 0;
}
//gcc prac1.c -o prac1 -lpthread
我是在gcc下编译的:gcc demo.c -o demo -lpthread