C-多线程
Posted at 2020-09-03 C 多线程
有如下代码
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
#include <stdio.h>#include <pthread.h>#include <unistd.h>#include <stdlib.h>volatile int th_num = 10;volatile int sum = 0;pthread_mutex_t lock;void *add_th(void *arg){ int in_arg = *(int *)arg; pthread_t tid; tid = pthread_self(); for(int i=0;i<2000;i++){ // 使用锁 pthread_mutex_lock(&lock); sum += 1; pthread_mutex_unlock(&lock); } printf("thread arg = %d\n",in_arg); printf("thread id = %lu\n",tid); th_num --; return NULL;}int main() { pthread_t handle; int re = -1; for (int i = th_num;i>0;i--){// 使用原有的i// int *arg = &i;// 新建变量 int *arg = malloc(sizeof(int)); *arg = i;//// int d = i;// int *arg = &d; re = pthread_create(&handle,NULL,add_th,arg); if(re == 0){ printf("创建线程成功\n"); }else { printf("创建线程失败,code %d\n",re); } } while (th_num > 0){ printf("查询线程是否已经退出,th_num : %d\n",th_num); sleep(1); } printf("sum = %d\n",sum); return 0;}
12345678910111213
#include <process.h>void th_testThread(void *arg) { // 线程处理 int *data = (int *)arg;}int main(int argc, char *argv[]) { int data = 2; _beginthread(th_testThread, 0, &data); // 主线程处理}
Previous post: C-Base Next post: git代码提交规范