#include 包含头文件
pthread_create:在 pthread_create 的第三个参数,是这么定义的:
void *(* _start_routine) (void *)1. 在第一个程序中,我们定义 子线程运行 函数地址
void *hello(struct message *str)
在 pthread_create中调用方式为:
pthread_create(&thread_id, NULL, (void *)*hello, &test);
或者是
void *a;
a=*hello;
pthread_create(&thread_id,NULL,(void *)a,&test);
2. 在第二个程序中,我们定义 子线程运行 函数
void thread(void)
在 pthread_create 中调用方式为:
ret=pthread_create(&id,NULL,(void *) thread,NULL);
thread 本身就是表示 函数的地址了
(void *) thread 还是转换为地址关于 *hello() 和 hello() 的解释看下一篇 - #include <pthread.h> //pthread_create
-
#include <stdio.h> //printf
-
-
struct message
-
{
-
int i;
-
int j;
-
};
-
-
void *hello(struct message *str) 带 *
-
{
-
printf("the arg.i is %d\n",str->i);
-
printf("the arg.j is %d\n",str->j);
-
}
-
-
int main(int argc, char *argv[])
-
{
-
struct message test;
-
pthread_t thread_id; //typedef unsigned long int pthread_t
-
test.i=10;
-
test.j=20;
-
-
void *a;
-
a=*hello; //两种方法都可以实现 ,注释掉代码的也可以实现
-
//pthread_create(&thread_id, NULL, (void *)*hello, &test);
-
pthread_create(&thread_id, NULL, (void *)a, &test);
-
printf("the new thread id is %u\n",thread_id);
-
pthread_join(thread_id,NULL); //在主线程等待子线程结束
-
}
-
/* void *(*__start_routine) (void *);
-
void *(* hello)
-
*/
- ywx@yuweixian:~/yu/professional/4$ gcc pthread_create.c -lpthread -o pthread_create
- ywx@yuweixian:~/yu/professional/4$ ./pthread_create
-
the arg.i is 10 子线程中执行
-
the arg.j is 20
-
the new thread id is 3078941552 在main 函数中
-
ywx@yuweixian:~/yu/professional/4$ ./pthread_create
-
the new thread id is 3078290288 在 main 函数中执行
-
the arg.i is 10 在子线程中执行
-
the arg.j is 20
我运行了两次 pthread_create程序,我们发现 这两次运行的结果不相同,这说明了两个线程争夺CPU资源的结果- #include <stdio.h>
-
#include <pthread.h>
-
-
void thread(void) 没有 *
-
{
-
int i;
-
for(i=0;i<3;i++)
-
printf("%d This is a pthread\n",i);
-
}
-
-
int main(void)
-
{
-
pthread_t id;
-
int i,ret;
-
ret=pthread_create(&id,NULL,(void *) thread,NULL);
-
if(ret!=0)
-
{
-
printf ("Create pthread error!n");
-
exit (1);
-
}
-
for(i=0;i<3;i++)
-
printf("%d This is the main process.\n",i);
-
-
pthread_join(id,NULL);
-
-
return (0);
-
}
运行结果不一样,说明两个线程在争夺CPU的过程- ywx@yuweixian:~/yu/professional/4$ ./pthread_create 0 This is the main process.
-
1 This is the main process.
-
2 This is the main process.
-
0 This is a pthread
-
1 This is a pthread
-
2 This is a pthread
-
ywx@yuweixian:~/yu/professional/4$ ./pthread_create
-
0 This is the main process.
-
1 This is the main process.
-
0 This is a pthread
-
1 This is a pthread
-
2 This is a pthread
-
2 This is the main process.
阅读(1561) | 评论(0) | 转发(0) |