linux 線程創建函數pthread_create的幾個傳參方式

最近在linux中用到了多線程的一些知識,網上找了一些有關pthread_create函數應用的例子,感覺收穫不少,在這裏貼出來以供方便學習之。

[文件] test1.c ~ 719B     

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
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void *start_routine(void *arg);
 
int main(int argc, char **argv)
{
  pthread_t tid;
  int code;
  int i;
 
  for (i = 0; i < 5; i++)
  {
    code = pthread_create(&tid, NULL, start_routine, (void *) i);
 
    if (code != 0)
    {
      fprintf(stderr, "Create new thread failed: %s\n", strerror(code));
      exit(1);
    }
 
    fprintf(stdout, "New thread created.\n");
  }
 
  pthread_exit((void *) 0);
}
 
void *start_routine(void *arg)
{
  int id = (int) arg;
 
  fprintf(stdout, "%s:%d:%s() running ...\n", __FILE__, __LINE__, __func__);
  fprintf(stdout, "id = %d\n", id);
 
  return ((void *) 0);
}
 
// vim:tabstop=8

2. [文件] test2.c ~ 793B     

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
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define THREADS_NUM 5
 
void *start_routine(void *arg);
 
int main(int argc, char **argv)
{
  pthread_t tid;
  int id[THREADS_NUM];
  int code;
  int i;
 
  for (i = 0; i < THREADS_NUM; i++)
  {
    id[i] = i;
     
    code = pthread_create(&tid, NULL, start_routine, &id[i]);
 
    if (code != 0)
    {
      fprintf(stderr, "Create new thread failed: %s\n", strerror(code));
      exit(1);
    }
 
    fprintf(stdout, "New thread created.\n");
  }
   
  pthread_exit((void *) 0);
}
 
void *start_routine(void *arg)
{
  int id = *(int *) arg;
 
  fprintf(stdout, "%s:%d:%s() running ...\n", __FILE__, __LINE__, __func__);
  fprintf(stdout, "id = %d\n", id);
 
  return ((void *) 0);
}
 
// vim:tabstop=8

3. [文件] test3.c ~ 714B     

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
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void *start_routine(void *arg);
 
int main(int argc, char **argv)
{
  pthread_t tid;
  int code;
  int i;
 
  for (i = 0; i < 5; i++)
  {
    code = pthread_create(&tid, NULL, start_routine, &i);
 
    if (code != 0)
    {
      fprintf(stderr, "Create new thread failed: %s\n", strerror(code));
      exit(1);
    }
 
    fprintf(stdout, "New thread created.\n");
  }
 
  pthread_exit((void *) 0);
}
 
void *start_routine(void *arg)
{
  int id = *(int *) arg;
 
  fprintf(stdout, "%s:%d:%s() running ...\n", __FILE__, __LINE__, __func__);
  fprintf(stdout, "id = %d\n", id);
 
  return ((void *) 0);
}
 
// vim:tabstop=8
發佈了607 篇原創文章 · 獲贊 9 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章