今天我们编写一个程序来实现线程有关的函数:
主要使用了平pthread_testcancelhan函数和pthread_cancel函数,
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void *tfn(void *arg)
{
int i;
i = (int)arg; //强转。
if (i == 2)
{
pthread_testcancel(); //自己添加取消点*/
pthread_cancel(pthread_self());
}
sleep(i); //通过i来区别每个线程
printf("I'm %dth thread, Thread_ID = %lu\n", i+1, pthread_self());
return NULL;
}
int main(int argc, char *argv[])
{
int n = 5, i;
pthread_t tid;
for (i = 0; i < n; i++) {
pthread_create(&tid, NULL, tfn, (void *)i);
//将i转换为指针,在tfn中再强转回整形。
}
sleep(n);
printf("I am main, I'm a thread!\n"
"main_thread_ID = %lu\n", pthread_self());//获取线程id
return 0;
}
程序运行结果:
I'm 1th thread, Thread_ID = 3086220176
I'm 2th thread, Thread_ID = 3075730320
I'm 4th thread, Thread_ID = 3054750608
I'm 5th thread, Thread_ID = 3044260752
I am main, I'm a thread!
main_thread_ID = 3086223040
函数综合使用实例:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void *tfn1(void *arg)
{
printf("thread 1 returning\n");
return (void *)111;
}
void *tfn2(void *arg)
{
printf("thread 2 exiting\n");
pthread_exit((void *)222);
}
void *tfn3(void *arg)
{
while (1) {
//printf("thread 3: I'm going to die in 3 seconds ...\n");
//sleep(1);
pthread_testcancel(); //自己添加取消点*/
}
return (void *)666;
}
int main(void)
{
pthread_t tid;
void *tret = NULL;
pthread_create(&tid, NULL, tfn1, NULL);
pthread_join(tid, &tret);
printf("thread 1 exit code = %d\n\n", (int)tret);
pthread_create(&tid, NULL, tfn2, NULL);
pthread_join(tid, &tret);
printf("thread 2 exit code = %d\n\n", (int)tret);
pthread_create(&tid, NULL, tfn3, NULL);
sleep(3);
pthread_cancel(tid);
pthread_join(tid, &tret);
printf("thread 3 exit code = %d\n", (int)tret);
return 0;
}