taohorse88 2015-12-03 11:42 采纳率: 0%
浏览 1401

两个线程打印到100,帮我看下为啥会打印到101

#include
#include
#include

int N = 100;
int n = 0;
pthread_mutex_t mutex;

void *func1()
{
while (n < N+1)
{
pthread_mutex_lock(&mutex);
printf ("%d 1\n", n);
n++;
pthread_mutex_unlock(&mutex);
}
if (n == N+1)
pthread_exit(NULL);
}

void *func2()
{
while (n < N+1)
{
pthread_mutex_lock(&mutex);
printf ("%d 2\n", n);
n++;
pthread_mutex_unlock(&mutex);
}

if (n == N+1)
    pthread_exit(NULL);

}

int main(void)
{
pthread_t pid1, pid2;
pthread_mutex_init(&mutex, NULL);

if ((pthread_create(&pid1, NULL, func1, NULL)) != 0)
    printf ("pthread create fail\n");

if ((pthread_create(&pid2, NULL, func2, NULL)) != 0)
        printf ("pthead create fail\n");

pthread_join(pid1, NULL);
pthread_join(pid2, NULL);

return 0;

}

输出如下:
0 2
1 2
2 2
3 2
4 2
5 2
6 2
7 2
8 2
9 2
10 2
11 2
12 2
13 2
14 2
15 2
16 2
17 2
18 2
19 2
20 2
21 2
22 2
23 2
24 2
25 2
26 2
27 2
28 2
29 2
30 2
31 2
32 2
33 2
34 2
35 2
36 2
37 2
38 2
39 2
40 2
41 2
42 2
43 2
44 2
45 2
46 2
47 2
48 2
49 2
50 2
51 2
52 2
53 2
54 2
55 2
56 2
57 2
58 2
59 2
60 2
61 2
62 2
63 2
64 2
65 2
66 2
67 2
68 2
69 2
70 2
71 2
72 2
73 2
74 2
75 2
76 2
77 2
78 2
79 2
80 2
81 2
82 2
83 2
84 2
85 2
86 2
87 2
88 2
89 2
90 2
91 2
92 2
93 2
94 2
95 2
96 2
97 2
98 2
99 2
100 2
101 1

还有一个问题,当我把pthread_mutex_init(&mutex, NULL);放到main函数外面时,编译一种报错
报错代码如下:
a.c:8:20: error: expected declaration specifiers or ‘...’ before ‘&’ token
pthread_mutex_init(&mutex, NULL);
^
In file included from /usr/include/time.h:37:0,
from /usr/include/pthread.h:24,
from a.c:3:
a.c:8:28: error: expected declaration specifiers or ‘...’ before ‘(’ token
pthread_mutex_init(&mutex, NULL);

  • 写回答

3条回答 默认 最新

  • only_yiyi_han 2015-12-03 12:00
    关注

    while (n < N+1) 让它小于N

    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案