Linuxのマルチスレッド符号化プロセスは、整理して、マルチスレッドの符号化処理のためのすべての一般的なAPIの最初の、pthreadのライブラリのサポートを成熟しています。
スレッド
並行性と並列性
シングルプロセッサ上でマルチスレッドプロセスでは、プロセッサは、同時実行するスレッド間で実行リソースを切り替えることができる
共有メモリ・マルチプロセッサ、マルチスレッド処理を、各スレッドのプロセスは、別個のCPUであってもよいです同時実行。
ユーザーレベルのスレッド
スレッドは、内部プロセスで表示され、すべて処理するために、共有アドレススペース、開いているファイル、およびその他のリソースなどのプロセスの雌ねじ、
以下の状態のは、各スレッドに固有のものです
- スレッドID
- 登録状況
- スタック
- シグナルマスク
- 優先順位
スレッド固有ストレージ
共通API
関心の主なポイントは3つのスレッド、スレッドの作成、スレッドとスレッドが待機出口を持っている、あなたは、Linuxのヘッダファイルを参照する必要があります
#include <pthread.h>
スレッドを作成します。
int pthread_create(pthread_t *tidp,const pthread_attr_t *attr, (void*)(*start_rtn)(void*),void *arg);
コンパイルとリンクのオプションが
ないのLinuxシステムではなく、POSIXスレッド・ライブラリー、そのライブラリ関数へのリンクを表示するには、コンパイル時または-lpthread -pthreadで追加する必要があるため、デフォルトのライブラリのpthreadライブラリに、-lpthreadすることの実装で間違っていません私たちは、システムエラーのエラー番号を修正するが、エラー値を返します。
高麗人参に分析
1.pthread_t tidpスレッドID、するために、各ユニークに1つのスレッドのポインタ
2.pthread_attr_tこのパラメータattrはPOSIXスレッドでは、NULLにデフォルト値を属性
3.(無効)( start_rtn)(void *型)スレッドの開始アドレス機能を実行する
複数のパラメータは、構造を定義する場合、関数の動作パラメータ4.
解決戻り値
スレッドが成功を作成している場合は、0を返し、間違った理由を返すスレッドの作成に失敗しました。
スレッドが正常に作成されている場合、tidpメモリユニットは、新しく作成されたスレッドのスレッドIDを指すように設定されています
サンプルコード
1 #include<stdio.h>
2 #include<pthread.h>
3 #include<string.h>
4 #include<sys/types.h>
5 #include<unistd.h>
6 void* printP(void* arg)
7 {
8 int i=0;
9
10 while (i != 100)
11 {
12 i++;
13 printf("This is the %d times print\n", i);
14 sleep(1);
15
16 }
17
18 }
19
20 bool CreateThread()
21 {
22 pthread_t m_pthread;
23 printf("This is new pthread\n");
24
25 //创建线程
26 if (pthread_create(&m_pthread, NULL, printP, NULL) != 0)
27 {
28 return false;
29 }
30 return true;
31
32 }
33
34 int main()
35 {
36 if(CreateThread() == false)
37 {
38 return -1;
39 }
40
41 int i = 0;
42 while(i < 100)
43 {
44 i++;
45 printf("This is the %d times say Hello!\n",i);
46 sleep(1);
47 }
48 return 1;
49 }
コードの実行中の結果
[jager@VM_0_10_centos pthread]$ ./test
This is new pthread
This is the 1 times say Hello!
This is the 1 times print
This is the 2 times say Hello!
This is the 2 times print
This is the 3 times say Hello!
This is the 3 times print
This is the 4 times say Hello!
This is the 4 times print
This is the 5 times say Hello!
This is the 5 times print
This is the 6 times say Hello!
注意
スレッドが作成された後、pスレッドとメインスレッドメインスレッドが交互に実行1.。