线程的创建和删除
多线程1.线程的创建和删除pthread_create - create a new threadSYNOPSIS #include <pthread.h>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
Compile and link with -pthread.#include <iostream>
#include<pthread.h>
using namespace std;
#define NUM 10
void* say_hello(void* args)
{
cout<<"Hello Runoob"<<endl;
return 0;
}
int main() {
std::cout << "Hello, World!" << std::endl;
pthread_t tids;
for(int i=0;i<NUM;i++)
{ //pthread_create (thread, attr, start_routine, arg) 产生新的线程 成功则返回0
int ret=pthread_create(&tids,NULL,say_hello,NULL);
if(ret!=0)
{
cout<<"pthread_create error: error_code= "<<ret<<endl;
}
}
pthread_exit(NULL);//pthread_exit (status)
return 0;
}
pthread_create 产生线程 pthread_exit 退出线程2. void (start_routine) (void *), void *arg); 传递参数形式#include<iostream>
#include<pthread.h>
#include<cstdlib>
#define NUM 5
using namespace std;
void *PrintHello(void *threadid)
{
int tid=*((int *)threadid);
cout<<"Hello Runoob ! ID: "<<tid<<endl;
pthread_exit(NULL);
}
int main()
{
pthread_t thread;
int index;
int rc,i;
for(i=0;i<NUM;i++)
{
cout<<"main(): 创建线程"<<endl;
index=i;//保存i的值
rc=pthread_create(&thread,NULL,PrintHello,(void *)&(index));//最后一个参数是向函数传递的参数
if(rc)
{
cout<<"Error:无法创建线程,"<<rc<<endl;
exit(-1);
}
}
pthread_exit(NULL);
}
页:
[1]