这篇博文就只说下,在ubuntu下 eclipse C++环境之下怎么创建线程

#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>

// the thread function
//libpthread.so

void * thread(void* arg)
{
pthread_t newid=0;
newid=pthread_self();
printf("this is a new thread %u",newid);
return NULL;
}
int main()
{
pthread_t thid;
printf("main thread is %u\n",(int)pthread_self());
if( pthread_create(&thid,NULL,&thread,NULL)!=0)
{
printf("thread create error %u\n",errno);
exit(1);
}
sleep(1);
exit(0);
}


这里面的代码只需要注意一点,在输出线程ID的时候一定要注意就是%u,才行,否则的话,会出问题,这是其一,其二呢,就是eclipse下线程的创建需要使用libpthread.so动态库,在eclipse中怎样使用呢?


在Libraries(-l)中添加pthread即可

,这样就完成了我们需要的操作



如果我们想要主线程等待子线程完成之后在进行唤醒,可以使用pthread_join操作,这样就不用再进行sleep了


/*
* main.cpp
*
* Created on: Jun 26, 2014
* Author: john
*/
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<errno.h>
// this is thread function
void* thread_function(void* a)
{
pthread_t thread_id=0;
printf("this is thread id %u\n",pthread_self());
return NULL;
}
int main()
{
int *status=0;
pthread_t newid=0;
printf("this is main thread id %u,\n",pthread_self());
if(pthread_create(&newid,NULL,thread_function,NULL)==0)
{
printf("thread create succefully\n");
}
pthread_join(newid,(void**)&status);
printf("the thread exit code is %d",*status);
return NULL;
}