- /* Name thread_create.c
- * Author dyli
- * date 20110615
- * Description 处理getpid()、pthread_self()、pthread_create()函数,
- * 并进行讨论主子线程的问题
- * */
- /***pthread_cancel()函数************************************************
- * 函数功能: 可以(在其它线程中)结束一个线程
- * 函数原型:
- * 返回值 : 返回值为0时,创建成功!!
- *
- * 所需库 :
- * 备注 :
- ****************************************************************/
- #include pthread.h>
- #include stdio.h>
- #include stdlib.h>
- int i=0;
- void *thread_func(void *argc)
- {
- int *val=argc;
- printf("Hi,man! I'm a son Thread\n\n");
- if(argc!=NULL)
- {
- //for(int i=0;i1000;i++)
- //c99不允许在for循环里初始化,会弹出在 C99 模式之外使用‘for’循环初始化声明错误
-
- for(;i50;i++)
- {
- ++i; //这两个不经意的++,产生了50内顺序显示奇数的效果
- printf("Now Show you the message:%d\n",*val);
- printf("Thread run %d times",i);
- }
- }
- }
- int main()
- {
- pthread_t tid;
- int t_arg =10;
- int err;
- err=pthread_create(&tid,NULL,thread_func,&t_arg); //--->带参数的pthread_create()函数
- if(err)//返回值为0时,创建成功!!
- {
- printf("create thread error!!\n");
- }
-
- sleep(1);
- printf("run in main Thread\n");
- if(pthread_cancel(tid))//---------------------------->func1结束线程
- {
- printf("向id为tid的线程发送了取消执行,但并不表示该线程会停止执行\n");
- }
- return 0;
- }
- [root@localhost thread_cancel]# ./thread_cancel
Hi,man! I'm a son Thread - Now Show you the message:10
Thread run 1 timesNow Show you the message:10
Thread run 3 timesNow Show you the message:10
Thread run 5 timesNow Show you the message:10
Thread run 7 timesNow Show you the message:10
Thread run 9 timesNow Show you the message:10
Thread run 11 timesNow Show you the message:10
Thread run 13 timesNow Show you the message:10
Thread run 15 timesNow Show you the message:10
Thread run 17 timesNow Show you the message:10
Thread run 19 timesNow Show you the message:10
Thread run 21 timesNow Show you the message:10
Thread run 23 timesNow Show you the message:10
Thread run 25 timesNow Show you the message:10
Thread run 27 timesNow Show you the message:10
Thread run 29 timesNow Show you the message:10
Thread run 31 timesNow Show you the message:10
Thread run 33 timesNow Show you the message:10
Thread run 35 timesNow Show you the message:10
Thread run 37 timesNow Show you the message:10
Thread run 39 timesNow Show you the message:10
Thread run 41 timesNow Show you the message:10
Thread run 43 timesNow Show you the message:10
Thread run 45 timesNow Show you the message:10
Thread run 47 timesNow Show you the message:10
Thread run 49 timesrun in main Thread
向id为tid的线程发送了取消执行,但并不表示该线程会停止执行
[root@localhost thread_cancel]#
- if(argc!=NULL)
- {
- for(int i=0;i1000;i++)
- //c99不允许在for循环里初始化,会弹出在 C99 模式之外使用‘for’循环初始化声明错误
- //for(;i50;i++)
- {
- ++i; //这两个不经意的++,产生了50内顺序显示奇数的效果
- printf("Now Show you the message:%d\n",*val);
- printf("Thread run %d times",i);
- }
- }
- [root@localhost thread_cancel]# make
- cc -c -o thread_cancel.o thread_cancel.c
- thread_cancel.c: 在函数‘thread_func’中:
- thread_cancel.c:30: 错误:在 C99 模式之外使用‘for’循环初始化声明
- make: *** [thread_cancel.o] 错误 1