c语言多线程pthread库概览
pthread.h #man pthread
pthread_t th; pthread_create(&th,NULL,a_func,NULL); #afunc :(void *)->(void*)
main不等待线程的,主死线程也死
pthread_join(th,NULL);等待线程th
- 多线程跑时,不知道谁先走,线程可交叉执行
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>void* myfunc(void* args){for(int i=0;i<10;i++){printf("myfunc + hello world\\n");}return NULL;
}
void* othfunc(void* args){for(int i = 1; i< 10;i++){printf("othfunc + %d\\n",i);}return NULL;
}int main(int argc,char argv){pthread_t th;pthread_t th1;pthread_create(&th,NULL,myfunc,NULL);pthread_create(&th1,NULL,othfunc,NULL);pthread_join(th,NULL);pthread_join(th1,NULL);return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>void* myfunc(void* args){for(int i=0;i<10;i++){printf("myfunc + hello world\\n");}return NULL;
}
void* othfunc(void* args){for(int i = 1; i< 10;i++){printf("othfunc + %d\\n",i);}return NULL;
}typedef struct {int first,second;
}Args;void* cntfunc(void* args){int i, sum = 0;Args* two_args = (Args*) args;int first = two_args->first;int second = two_args->second;for(i = first;i<second;i++){sum += i;}printf("%d\\n", sum);return NULL;
}int main(int argc,char argv){pthread_t th;pthread_t th1;pthread_create(&th,NULL,myfunc,NULL);pthread_create(&th1,NULL,othfunc,NULL);pthread_join(th,NULL);pthread_join(th1,NULL);Args arg = {0,2500};Args arg1 = {1110,5500};pthread_create(&th,NULL,cntfunc,&arg);pthread_create(&th1,NULL,cntfunc,&arg1);pthread_join(th,NULL);pthread_join(th1,NULL);return 0;
}
数据竞争时就要加锁
pthread_mutex_t lock;
pthread_mutex_init(&lock,NULL);
对代码段加锁
pthread_mutex_lock(&lock);
s++;
pthread_mutex_unlock(&lock);
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>pthread_mutex_t lock;
int s = 0;
void* myfunc(void* args){pthread_mutex_lock(&lock);int i = 0;for(;i<10000;i++){s++;}pthread_mutex_unlock(&lock);return NULL;
}int main(int argc,char argv){pthread_mutex_init(&lock,NULL);pthread_t th;pthread_t th1;pthread_create(&th,NULL,myfunc,NULL);pthread_create(&th1,NULL,myfunc,NULL);pthread_join(th,NULL);pthread_join(th1,NULL);printf("%d\\n", s);return 0;
}
it works,但是这好像没有用到多线程,因为一旦加上上面的锁,程序也只能按序执行
gcc pth.c -lpthread -o main
time ./main