-
Notifications
You must be signed in to change notification settings - Fork 0
/
C语言多线程示例.html
1190 lines (844 loc) · 60.6 KB
/
C语言多线程示例.html
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="keywords" content="c语言多线程示例, 技术分享,学习记录。">
<meta name="description" content="一个简单的C语言多进程示例">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="renderer" content="webkit|ie-stand|ie-comp">
<meta name="mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="referrer" content="no-referrer-when-downgrade">
<!-- Global site tag (gtag.js) - Google Analytics -->
<title>c语言多线程示例 | 操作系统技术分享</title>
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
<link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
<link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
<link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
<link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
<link rel="stylesheet" type="text/css" href="/css/matery.css">
<link rel="stylesheet" type="text/css" href="/css/my.css">
<script src="/libs/jquery/jquery-3.6.0.min.js"></script>
<meta name="generator" content="Hexo 5.4.1"></head>
<body>
<header class="navbar-fixed">
<nav id="headNav" class="bg-color nav-transparent">
<div id="navContainer" class="nav-wrapper container">
<div class="brand-logo">
<a href="/" class="waves-effect waves-light">
<img src="/medias/logo.png" class="logo-img" alt="LOGO">
<span class="logo-span">操作系统技术分享</span>
</a>
</div>
<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
<li class="hide-on-med-and-down nav-item">
<a href="/" class="waves-effect waves-light">
<i class="fas fa-home" style="zoom: 0.6;"></i>
<span>首页</span>
</a>
</li>
<li class="hide-on-med-and-down nav-item">
<a href="/tags" class="waves-effect waves-light">
<i class="fas fa-tags" style="zoom: 0.6;"></i>
<span>标签</span>
</a>
</li>
<li class="hide-on-med-and-down nav-item">
<a href="/categories" class="waves-effect waves-light">
<i class="fas fa-bookmark" style="zoom: 0.6;"></i>
<span>分类</span>
</a>
</li>
<li class="hide-on-med-and-down nav-item">
<a href="/archives" class="waves-effect waves-light">
<i class="fas fa-archive" style="zoom: 0.6;"></i>
<span>归档</span>
</a>
</li>
<li class="hide-on-med-and-down nav-item">
<a href="/about" class="waves-effect waves-light">
<i class="fas fa-user-circle" style="zoom: 0.6;"></i>
<span>关于</span>
</a>
</li>
<li>
<a href="#searchModal" class="modal-trigger waves-effect waves-light">
<i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
</a>
</li>
</ul>
<div id="mobile-nav" class="side-nav sidenav">
<div class="mobile-head bg-color">
<img src="/medias/logo.png" class="logo-img circle responsive-img">
<div class="logo-name">操作系统技术分享</div>
<div class="logo-desc">
这里是农光鑫的个人博客
</div>
</div>
<ul class="menu-list mobile-menu-list">
<li class="m-nav-item">
<a href="/" class="waves-effect waves-light">
<i class="fa-fw fas fa-home"></i>
首页
</a>
</li>
<li class="m-nav-item">
<a href="/tags" class="waves-effect waves-light">
<i class="fa-fw fas fa-tags"></i>
标签
</a>
</li>
<li class="m-nav-item">
<a href="/categories" class="waves-effect waves-light">
<i class="fa-fw fas fa-bookmark"></i>
分类
</a>
</li>
<li class="m-nav-item">
<a href="/archives" class="waves-effect waves-light">
<i class="fa-fw fas fa-archive"></i>
归档
</a>
</li>
<li class="m-nav-item">
<a href="/about" class="waves-effect waves-light">
<i class="fa-fw fas fa-user-circle"></i>
关于
</a>
</li>
<li><div class="divider"></div></li>
<li>
<a href="https://gitee.com/nongguangxin" class="waves-effect waves-light" target="_blank">
<i class="fab fa-github-square fa-fw"></i>Fork Me
</a>
</li>
</ul>
</div>
</div>
<style>
.nav-transparent .github-corner {
display: none !important;
}
.github-corner {
position: absolute;
z-index: 10;
top: 0;
right: 0;
border: 0;
transform: scale(1.1);
}
.github-corner svg {
color: #0f9d58;
fill: #fff;
height: 64px;
width: 64px;
}
.github-corner:hover .octo-arm {
animation: a 0.56s ease-in-out;
}
.github-corner .octo-arm {
animation: none;
}
@keyframes a {
0%,
to {
transform: rotate(0);
}
20%,
60% {
transform: rotate(-25deg);
}
40%,
80% {
transform: rotate(10deg);
}
}
</style>
<a href="https://gitee.com/nongguangxin" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
data-tooltip="Fork Me" data-position="left" data-delay="50">
<svg viewBox="0 0 250 250" aria-hidden="true">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
fill="currentColor" class="octo-body"></path>
</svg>
</a>
</nav>
</header>
<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/15.jpg')">
<div class="container" style="right: 0px;left: 0px;">
<div class="row">
<div class="col s12 m12 l12">
<div class="brand">
<h1 class="description center-align post-title">c语言多线程示例</h1>
</div>
</div>
</div>
</div>
</div>
<main class="post-container content">
<link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
#articleContent h1::before,
#articleContent h2::before,
#articleContent h3::before,
#articleContent h4::before,
#articleContent h5::before,
#articleContent h6::before {
display: block;
content: " ";
height: 100px;
margin-top: -100px;
visibility: hidden;
}
#articleContent :focus {
outline: none;
}
.toc-fixed {
position: fixed;
top: 64px;
}
.toc-widget {
width: 345px;
padding-left: 20px;
}
.toc-widget .toc-title {
padding: 35px 0 15px 17px;
font-size: 1.5rem;
font-weight: bold;
line-height: 1.5rem;
}
.toc-widget ol {
padding: 0;
list-style: none;
}
#toc-content {
padding-bottom: 30px;
overflow: auto;
}
#toc-content ol {
padding-left: 10px;
}
#toc-content ol li {
padding-left: 10px;
}
#toc-content .toc-link:hover {
color: #42b983;
font-weight: 700;
text-decoration: underline;
}
#toc-content .toc-link::before {
background-color: transparent;
max-height: 25px;
position: absolute;
right: 23.5vw;
display: block;
}
#toc-content .is-active-link {
color: #42b983;
}
#floating-toc-btn {
position: fixed;
right: 15px;
bottom: 76px;
padding-top: 15px;
margin-bottom: 0;
z-index: 998;
}
#floating-toc-btn .btn-floating {
width: 48px;
height: 48px;
}
#floating-toc-btn .btn-floating i {
line-height: 48px;
font-size: 1.4rem;
}
</style>
<div class="row">
<div id="main-content" class="col s12 m12 l9">
<!-- 文章内容详情 -->
<div id="artDetail">
<div class="card">
<div class="card-content article-info">
<div class="row tag-cate">
<div class="col s7">
<div class="article-tag">
<a href="/tags/pthread/">
<span class="chip bg-color">pthread</span>
</a>
<a href="/tags/Multithreading/">
<span class="chip bg-color">Multithreading</span>
</a>
</div>
</div>
<div class="col s5 right-align">
<div class="post-cate">
<i class="fas fa-bookmark fa-fw icon-category"></i>
<a href="/categories/C-C/" class="post-category">
C/C++
</a>
</div>
</div>
</div>
<div class="post-info">
<div class="post-date info-break-policy">
<i class="far fa-calendar-minus fa-fw"></i>发布日期:
2021-01-08
</div>
<div class="post-date info-break-policy">
<i class="far fa-calendar-check fa-fw"></i>更新日期:
2022-03-01
</div>
<div class="info-break-policy">
<i class="far fa-file-word fa-fw"></i>文章字数:
1.2k
</div>
<div class="info-break-policy">
<i class="far fa-clock fa-fw"></i>阅读时长:
5 分
</div>
</div>
</div>
<hr class="clearfix">
<!-- 是否加载使用自带的 prismjs. -->
<link rel="stylesheet" href="/libs/prism/prism.min.css">
<div class="card-content article-card-content">
<div id="articleContent">
<h2 id="0-简介"><a href="#0-简介" class="headerlink" title="0. 简介"></a>0. 简介</h2><p>当程序的性能到达瓶颈时,常用的解决方法是使用多线程,将任务或数据分割,使用不同的线程分别来处理,充分利用处理器的多核特性。</p>
<p><code>pthread</code>(<code>POSIX thread</code>)是<code>Linux</code>提供的一套兼容<code>POSIX</code>接口的线程库,是常用的线程库。</p>
<h2 id="1-线程创建"><a href="#1-线程创建" class="headerlink" title="1. 线程创建"></a>1. 线程创建</h2><p>线程创建接口:</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><pthread.h></span></span>
<span class="token keyword">int</span> <span class="token function">pthread_create</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span> <span class="token operator">*</span>thread<span class="token punctuation">,</span> <span class="token keyword">const</span> <span class="token class-name">pthread_attr_t</span> <span class="token operator">*</span>attr<span class="token punctuation">,</span>
<span class="token keyword">void</span> <span class="token operator">*</span><span class="token punctuation">(</span><span class="token operator">*</span>start_routine<span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token keyword">void</span> <span class="token operator">*</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span>arg<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p><code>pthread_create</code>是<code>pthread</code>库的线程创建接口,使用这个接口需要包含<code>pthread.h</code>头文件。线程创建成功时返回0,失败时返回相应错误码。</p>
<p>各个参数的含义如下:</p>
<ul>
<li>thread 创建的线程的线程ID,用来唯一区别一个线程。</li>
<li>attr 线程属性</li>
<li>start_routine 线程执行函数</li>
<li>arg 要传递的参数</li>
</ul>
<p><strong>示例:</strong></p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token keyword">const</span> <span class="token class-name">size_t</span> threads <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">;</span>
<span class="token class-name">pthread_t</span> thread_arr<span class="token punctuation">[</span>threads<span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token function">memset</span><span class="token punctuation">(</span>thread_arr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> threads<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> retval <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">size_t</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator"><</span> threads<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
retval <span class="token operator">=</span> <span class="token function">pthread_create</span><span class="token punctuation">(</span><span class="token operator">&</span><span class="token punctuation">(</span>thread_arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token constant">NULL</span><span class="token punctuation">,</span> thread_handle<span class="token punctuation">,</span> <span class="token operator">&</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>retval<span class="token punctuation">)</span> <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"thread_arr i=%ld create failed.\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">usleep</span><span class="token punctuation">(</span><span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里我们创建10个线程,并使用一个数组<code>thread_arr</code>储存创建的好的线程的ID,用于后续的线程合并。</p>
<p><code>pthread_create</code>的第二个参数一般情况下设置为<code>NULL</code>,<code>thread_handle</code>就是要执行的线程函数,最后一个参数中传入<code>i</code>作为参数,若要传入多个参数可以使用结构体。</p>
<p>休眠5000微秒是为了完成线程中参数的复制,不然如果在参数完成复制前参数被改变,将会导致传入的参数错误。</p>
<h2 id="2-线程函数"><a href="#2-线程函数" class="headerlink" title="2. 线程函数"></a>2. 线程函数</h2><p>线程函数的函数签名需为<code>void* func(void* arg)</code>,即参数和返回值的类型都是void指针。</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token keyword">void</span> <span class="token operator">*</span><span class="token function">thread_handle</span><span class="token punctuation">(</span><span class="token keyword">void</span> <span class="token operator">*</span>arg<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
<span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token operator">*</span><span class="token punctuation">(</span><span class="token keyword">int</span> <span class="token operator">*</span><span class="token punctuation">)</span>arg<span class="token punctuation">;</span>
<span class="token class-name">pthread_t</span> <span class="token operator">*</span>pid <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">pthread_t</span> <span class="token operator">*</span><span class="token punctuation">)</span><span class="token function">malloc</span><span class="token punctuation">(</span><span class="token keyword">sizeof</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">*</span>pid <span class="token operator">=</span> <span class="token function">pthread_self</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"run thread id=%ld, i=%d\n"</span><span class="token punctuation">,</span> <span class="token operator">*</span>pid<span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">pthread_exit</span><span class="token punctuation">(</span>pid<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在线程函数中,我们先复制了传入的参数;因为参数是指针,为了防止参数被改变,应先在参数在main中被改变前拷贝一份到当前线程。</p>
<p>函数中分配了一份内存来存放线程的ID。因为要返回的是一个指针,如果返回的是一个指向栈对象的指针,线程退出后临时对象会被释放,当我们获取时,获取到的就是一个错误或不存在的值。当然也可以使用全局变量传递返回值。</p>
<p>在这里我们使用<code>pthread_exit</code>来退出线程并返回相应的值。<code>pthread_exit</code>的定义如下:</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><pthread.h></span></span>
<span class="token keyword">void</span> <span class="token function">pthread_exit</span><span class="token punctuation">(</span><span class="token keyword">void</span> <span class="token operator">*</span>retval<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>除了使用上述函数来退出外,还可以使用<code>return</code>语句,或<code>exit</code>,<code>pthread_cancel</code>。</p>
<h2 id="3-线程合并"><a href="#3-线程合并" class="headerlink" title="3. 线程合并"></a>3. 线程合并</h2><pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token keyword">void</span> <span class="token operator">*</span>thret<span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator"><</span> threads<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>thread_arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token function">pthread_join</span><span class="token punctuation">(</span>thread_arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token operator">&</span>thret<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"thread_arr[%d] return %ld.\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">,</span> <span class="token operator">*</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span> <span class="token operator">*</span><span class="token punctuation">)</span>thret<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">free</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span> <span class="token operator">*</span><span class="token punctuation">)</span>thret<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们使用<code>pthread_join</code>接口等待线程执行完毕,并获取返回值。函数的定义如下:</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><pthread.h></span></span>
<span class="token keyword">int</span> <span class="token function">pthread_join</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span> thread<span class="token punctuation">,</span> <span class="token keyword">void</span> <span class="token operator">*</span><span class="token operator">*</span>retval<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>第一个参数为要等待的线程ID,第二个参数为线程的返回值。还要注意释放在线程中分配的用来储存返回值的内存。</p>
<h2 id="4-完整示例"><a href="#4-完整示例" class="headerlink" title="4. 完整示例"></a>4. 完整示例</h2><pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><stdio.h></span></span>
<span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><unistd.h></span></span>
<span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><string.h></span></span>
<span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><pthread.h></span></span>
<span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><stdlib.h></span></span>
<span class="token keyword">void</span> <span class="token operator">*</span><span class="token function">thread_handle</span><span class="token punctuation">(</span><span class="token keyword">void</span> <span class="token operator">*</span>arg<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
<span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token operator">*</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token operator">*</span><span class="token punctuation">)</span>arg<span class="token punctuation">;</span>
<span class="token class-name">pthread_t</span><span class="token operator">*</span> pid <span class="token operator">=</span> <span class="token function">malloc</span><span class="token punctuation">(</span><span class="token keyword">sizeof</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">*</span>pid <span class="token operator">=</span> <span class="token function">pthread_self</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"run thread id=%ld, i=%d\n"</span><span class="token punctuation">,</span> <span class="token operator">*</span>pid<span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">pthread_exit</span><span class="token punctuation">(</span>pid<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">int</span> argc<span class="token punctuation">,</span> <span class="token keyword">char</span> <span class="token keyword">const</span> <span class="token operator">*</span>argv<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
<span class="token keyword">const</span> <span class="token class-name">size_t</span> threads <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">;</span>
<span class="token class-name">pthread_t</span> thread_arr<span class="token punctuation">[</span>threads<span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token function">memset</span><span class="token punctuation">(</span>thread_arr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> threads<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> retval <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">size_t</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator"><</span> threads<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
retval <span class="token operator">=</span> <span class="token function">pthread_create</span><span class="token punctuation">(</span><span class="token operator">&</span><span class="token punctuation">(</span>thread_arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token constant">NULL</span><span class="token punctuation">,</span> thread_handle<span class="token punctuation">,</span> <span class="token operator">&</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>retval<span class="token punctuation">)</span>
<span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"thread_arr i=%ld create failed.\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">usleep</span><span class="token punctuation">(</span><span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">void</span><span class="token operator">*</span> thret<span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator"><</span> threads<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>thread_arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
<span class="token function">pthread_join</span><span class="token punctuation">(</span>thread_arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token operator">&</span>thret<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"thread_arr[%d] return %ld.\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">,</span> <span class="token operator">*</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span><span class="token operator">*</span><span class="token punctuation">)</span>thret<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">free</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">pthread_t</span><span class="token operator">*</span><span class="token punctuation">)</span>thret<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"main exit.\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>编译执行:</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">$ gcc pthread2.c -lpthread
$ ./a.out
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000393443072</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">0</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000384939776</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">1</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000376547072</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">2</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000297481984</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">3</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000289089280</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">4</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000280696576</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">5</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000272303872</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">6</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000263911168</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">7</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000255518464</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">8</span>
run thread <span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">140000247125760</span>, <span class="token assign-left variable">i</span><span class="token operator">=</span><span class="token number">9</span>
thread_arr<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000393443072</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000384939776</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000376547072</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000297481984</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000289089280</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000280696576</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">6</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000272303872</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">7</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000263911168</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">8</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000255518464</span>.
thread_arr<span class="token punctuation">[</span><span class="token number">9</span><span class="token punctuation">]</span> <span class="token builtin class-name">return</span> <span class="token number">140000247125760</span>.
main exit.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>编译的时候注意需要链接<code>pthread</code>库。否则不能使用相关的接口。可以看到,线程的ID和传入的参数都被线程正确打印出来了,返回的线程ID也获取并打印。</p>
<h2 id="5-后话"><a href="#5-后话" class="headerlink" title="5. 后话"></a>5. 后话</h2><p>关于多线程有很多的内容,比如线程分离,线程属性,线程同步等。这里只是一个简单的多线程示例。</p>
<p>实力有限,代码仅供参考,如有错误或不合适的地方欢迎提出讨论。</p>
</div>
<hr/>
<div class="reprint" id="reprint-statement">
<div class="reprint__author">
<span class="reprint-meta" style="font-weight: bold;">
<i class="fas fa-user">
文章作者:
</i>
</span>
<span class="reprint-info">
<a href="https://nonguangxin.cn" rel="external nofollow noreferrer">农光鑫</a>
</span>
</div>
<div class="reprint__type">
<span class="reprint-meta" style="font-weight: bold;">
<i class="fas fa-link">
文章链接:
</i>
</span>
<span class="reprint-info">
<a href="https://nonguangxin.cn/C%E8%AF%AD%E8%A8%80%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%A4%BA%E4%BE%8B.html">https://nonguangxin.cn/C%E8%AF%AD%E8%A8%80%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%A4%BA%E4%BE%8B.html</a>
</span>
</div>
<div class="reprint__notice">
<span class="reprint-meta" style="font-weight: bold;">
<i class="fas fa-copyright">
版权声明:
</i>
</span>
<span class="reprint-info">
本博客所有文章除特別声明外,均采用
<a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a>
许可协议。转载请注明来源
<a href="https://nonguangxin.cn" target="_blank">农光鑫</a>
!
</span>
</div>
</div>
<script async defer>
document.addEventListener("copy", function (e) {
let toastHTML = '<span>复制成功,请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
M.toast({html: toastHTML})
});
function navToReprintStatement() {
$("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
}
</script>
<div class="tag_share" style="display: block;">
<div class="post-meta__tag-list" style="display: inline-block;">
<div class="article-tag">
<a href="/tags/pthread/">
<span class="chip bg-color">pthread</span>
</a>
<a href="/tags/Multithreading/">
<span class="chip bg-color">Multithreading</span>
</a>
</div>
</div>
<div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
<link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">
<div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享!</p>"></div>
<script src="/libs/share/js/social-share.min.js"></script>
</div>
</div>
</div>
</div>
</div>
<article id="prenext-posts" class="prev-next articles">
<div class="row article-row">
<div class="article col s12 m6" data-aos="fade-up">
<div class="article-badge left-badge text-color">
<i class="fas fa-chevron-left"></i> 上一篇</div>
<div class="card">
<a href="/GCC11%E7%9A%84C-module%E7%A4%BA%E4%BE%8B.html">
<div class="card-image">
<img src="/medias/featureimages/20.jpg" class="responsive-img" alt="GCC11的C++-module示例">
<span class="card-title">GCC11的C++-module示例</span>
</div>
</a>
<div class="card-content article-content">
<div class="summary block-with-text">
记录从源码编译GCC11的过程和一个简单的C++-module示例
</div>
<div class="publish-info">
<span class="publish-date">
<i class="far fa-clock fa-fw icon-date"></i>2021-01-21
</span>
<span class="publish-author">
<i class="fas fa-bookmark fa-fw icon-category"></i>
<a href="/categories/C-C/" class="post-category">
C/C++
</a>
</span>
</div>
</div>
<div class="card-action article-tags">
<a href="/tags/GCC/">
<span class="chip bg-color">GCC</span>
</a>
<a href="/tags/GCC11/">
<span class="chip bg-color">GCC11</span>
</a>
<a href="/tags/module/">
<span class="chip bg-color">module</span>
</a>
<a href="/tags/C/">
<span class="chip bg-color">C++</span>
</a>
</div>
</div>
</div>
<div class="article col s12 m6" data-aos="fade-up">
<div class="article-badge right-badge text-color">
下一篇 <i class="fas fa-chevron-right"></i>
</div>
<div class="card">
<a href="/top%E5%91%BD%E4%BB%A4%E8%BE%93%E5%87%BA%E7%AE%80%E4%BB%8B.html">
<div class="card-image">
<img src="/medias/featureimages/22.jpg" class="responsive-img" alt="top命令输出简介">
<span class="card-title">top命令输出简介</span>
</div>
</a>
<div class="card-content article-content">
<div class="summary block-with-text">
简要介绍top命令输出信息
</div>
<div class="publish-info">
<span class="publish-date">
<i class="far fa-clock fa-fw icon-date"></i>2021-01-08
</span>
<span class="publish-author">
<i class="fas fa-bookmark fa-fw icon-category"></i>
<a href="/categories/tools/" class="post-category">
tools
</a>
</span>
</div>
</div>
<div class="card-action article-tags">
<a href="/tags/top/">
<span class="chip bg-color">top</span>
</a>
</div>
</div>
</div>
</div>
</article>
</div>
<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>
<!-- 是否加载使用自带的 prismjs. -->
<script type="text/javascript" src="/libs/prism/prism.min.js"></script>
<!-- 代码语言 -->
<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>
<!-- 代码块复制 -->
<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>
<!-- 代码块收缩 -->
<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>
</div>
<div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
<div class="toc-widget card" style="background-color: white;">
<div class="toc-title"><i class="far fa-list-alt"></i> 目录</div>
<div id="toc-content"></div>
</div>
</div>
</div>
<!-- TOC 悬浮按钮. -->
<div id="floating-toc-btn" class="hide-on-med-and-down">
<a class="btn-floating btn-large bg-color">
<i class="fas fa-list-ul"></i>
</a>
</div>
<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
$(function () {
tocbot.init({
tocSelector: '#toc-content',
contentSelector: '#articleContent',
headingsOffset: -($(window).height() * 0.4 - 45),
collapseDepth: Number('0'),
headingSelector: 'h1, h2, h3, h4. h5, h6'
});
// Set scroll toc fixed.
let tocHeight = parseInt($(window).height() * 0.4 - 64);
let $tocWidget = $('.toc-widget');
$(window).scroll(function () {
let scroll = $(window).scrollTop();
/* add post toc fixed. */
if (scroll > tocHeight) {
$tocWidget.addClass('toc-fixed');
} else {
$tocWidget.removeClass('toc-fixed');
}
});
/* 修复文章卡片 div 的宽度. */
let fixPostCardWidth = function (srcId, targetId) {
let srcDiv = $('#' + srcId);
if (srcDiv.length === 0) {
return;
}
let w = srcDiv.width();
if (w >= 450) {
w = w + 21;
} else if (w >= 350 && w < 450) {
w = w + 18;
} else if (w >= 300 && w < 350) {
w = w + 16;
} else {
w = w + 14;
}
$('#' + targetId).width(w);
};
// 切换TOC目录展开收缩的相关操作.
const expandedClass = 'expanded';
let $tocAside = $('#toc-aside');
let $mainContent = $('#main-content');
$('#floating-toc-btn .btn-floating').click(function () {
if ($tocAside.hasClass(expandedClass)) {
$tocAside.removeClass(expandedClass).hide();
$mainContent.removeClass('l9');
} else {
$tocAside.addClass(expandedClass).show();
$mainContent.addClass('l9');
}
fixPostCardWidth('artDetail', 'prenext-posts');
});
});
</script>
</main>
<footer class="page-footer bg-color">
<div class="container row center-align"
style="margin-bottom: 0px !important;">
<div class="col s12 m8 l8 copy-right">
Copyright ©
<span id="year">2020-2022</span>
<a href="/about" target="_blank">农光鑫</a>
| Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
| Theme <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
<br>
<i class="fas fa-chart-area"></i> 站点总字数: <span
class="white-color">102.9k</span>
<span id="busuanzi_container_site_pv">
| <i class="far fa-eye"></i> 总访问量:
<span id="busuanzi_value_site_pv" class="white-color"></span>
</span>
<span id="busuanzi_container_site_uv">
| <i class="fas fa-users"></i> 总访问人数:
<span id="busuanzi_value_site_uv" class="white-color"></span>
</span>
<br>
<!-- 运行天数提醒. -->
<br>
<span id="icp"><img src="/medias/icp.png"
style="vertical-align: text-bottom;"/>
<a href="https://beian.miit.gov.cn" target="_blank">桂ICP备2022006245号</a>
</span>
</div>
<div class="col s12 m4 l4 social-link ">
<a href="https://gitee.com/nongguangxin" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
<i class="fab fa-github"></i>
</a>
<a href="mailto:614837785@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
<i class="fas fa-envelope-open"></i>
</a>
<a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=614837785" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 614837785" data-position="top" data-delay="50">
<i class="fab fa-qq"></i>
</a>