1
|
#include
|
1
2
|
int
pthread_create(pthread_t *tidp,
const
pthread_attr_t *attr,
(
void
*)(*start_rtn)(
void
*),
void
*arg);
|
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
|
#include
#include
#include
#include
#include
void
printids(
const
char
*s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf
(
"%s pid %u tid %u (0x%x)\n"
, s, (unsigned
int
) pid,
(unsigned
int
) tid, (unsigned
int
) tid);
}
void
*thr_fn(
void
*arg)
{
printids(
"new thread: "
);
return
NULL;
}
int
main(
void
)
{
int
err;
pthread_t ntid;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if
(err != 0)
printf
(
"can't create thread: %s\n"
,
strerror
(err));
printids(
"main thread:"
);
pthread_join(ntid,NULL);
return
EXIT_SUCCESS;
}
|
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
|
#include
#include
#include
#include
#define NUM_THREADS 8
void
*PrintHello(
void
*args)
{
int
thread_arg;
sleep(1);
thread_arg = (
int
)(*((
int
*)args));
printf
(
"Hello from thread %d\n"
, thread_arg);
return
NULL;
}
int
main(
void
)
{
int
rc,t;
pthread_t
thread
[NUM_THREADS];
for
( t = 0; t < NUM_THREADS; t++)
{
printf
(
"Creating thread %d\n"
, t);
rc = pthread_create(&
thread
[t], NULL, PrintHello, &t);
if
(rc)
{
printf
(
"ERROR; return code is %d\n"
, rc);
return
EXIT_FAILURE;
}
}
sleep(5);
for
( t = 0; t < NUM_THREADS; t++)
pthread_join(
thread
[t], NULL);
return
EXIT_SUCCESS;
}
|
$ ./a.out
向线程函数传递参数详解:
向线程函数传递参数分为两种:
(1)线程函数只有一个参数的情况:直接定义一个变量通过应用传给线程函数。
例子:
#include
#include
using namespace std;
pthread_t thread;
void fn(void *arg)
{
int i = *(int *)arg;
cout<<"i = "< return ((void *)0);
}
int main()
{
int err1;
int i=10;
err1 = pthread_create(&thread, NULL, fn, &i);
pthread_join(thread, NULL);
}
2、线程函数有多个参数的情况:这种情况就必须申明一个结构体来包含所有的参数,然后在传入线程函数,具体如下:
例子:
首先定义一个结构体:
struct parameter
{
int size,
int count;
。。。。。
。。。
};
然后在main函数将这个结构体指针,作为void *形参的实际参数传递
struct parameter arg;
通过如下的方式来调用函数:
void fn(void *arg)
{
int i = *(int *)arg;
cout<<"i = "<
return ((void *)0);
}