long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

C-多线程

Posted at 2020-09-03 C 多线程 

多线程的坑

有如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#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;
}
分析
  1. 将for循环中的i,直接作为线程的入参,有什么问题吗?
    直接将i作为入参,后面的几个线程都是使用同一个i变量。i后面的值会影响前面的值。需要使用新的变量作为入参才能满足使用要求。
  2. 多个线程对同一个变量进行操作需要加锁,使用volatile是无法避免的。必须使用锁才能保证数据不会出现冲突。
    注意:这里的多线程是基于linux系统的,windows使用线程开发方式不一样。

windows 多线程开发

windows创建一个线程

1
2
3
4
5
6
7
8
9
10
11
12
13
#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);

// 主线程处理
}

Share 

 Previous post: C-Base Next post: git代码提交规范 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo