create.c
#include
#include
#include
void* Entry1(void* arg)
{
(void)arg;
while(1)
{
printf("hello world1!\n");
sleep(1);
}
return NULL;
}
void* Entry2(void* arg)
{
(void)arg;
while(1)
{
printf("hello world2!\n");
sleep(1);
}
return NULL;
}
int main()
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, Entry1, NULL);
pthread_create(&tid2, NULL, Entry2, NULL);
while(1)
{
printf("Main is here.\n");
sleep(1);
}
return 0;
}
运行结果:三个线程通过cpu的调度交替运行。
join.c
#include
#include
#include
#include
#include
void *thread1(void* arg)
{
(void)arg;
printf("I am thread1.\n");
int *p=(int*)malloc(sizeof(int));
*p=1;
return (void*)p;
}
void * thread2(void* arg)
{
(void)arg;
printf("I am thread2.\n");
int *p = (int*)malloc(sizeof(int));
*p=2;
return (void*)p;
}
void * thread3(void* arg)
{
(void)arg;
while(1)
{
printf("I am thread3.\n");
sleep(1);
}
return NULL;
}
int main()
{
pthread_t tid;
void * ret;
pthread_create(&tid,NULL, thread1, NULL);
pthread_join(tid,&ret);
printf("The thread is return, id %X, return value:%d \n",(unsigned int)tid, *(int*)ret);
free(ret);
pthread_create(&tid,NULL, thread2, NULL);
pthread_join(tid,&ret);
printf("The thread is return, id %X, return value:%d \n",(unsigned int)tid, *(int*)ret);
free(ret);
pthread_create(&tid,NULL, thread3, NULL);
sleep(2);
pthread_cancel(tid);
pthread_join(tid,&ret);
if(ret==PTHREAD_CANCELED)
{
printf("The thread is return, id %X, return value:PTHREAD_CANCELED\n",(unsigned int)tid);
}
else
{
printf("The thread is return, id %X, return code :NULL\n",(unsigned int)tid);
}
return 0;
}
运行结果:通过pthread_join函数回收已经结束的线程,之后再次创建线程时该地址被复用。当线程被pthread_cancel终止后,
value 的值等于系统定义的宏 PTHREAD_CANCELED (注意是 value 不是 *value)
detach.c
#include
#include
#include
#include
#include
void* thread(void* arg)
{
pthread_detach(pthread_self());
printf("%s \n",(char*)arg);
return NULL;
}
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, thread, (void*)"hello world.");
int ret;
sleep(1);
ret=pthread_join(tid, NULL);
if(ret==0)
{
printf("waiting success.\n");
}
else
{
printf("waiting failed\n");
}
return ret;
}
运行结果: sleep(1)保证 pthread_detach 先于 pthread_join 被调用。