头文件
#include<pthread.h>
函数声明
1 2 |
|
返回值
若线程创建成功,则返回0。若线程创建失败,则返回出错编号,并且*thread中的内容是未定义的。
返回成功时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于指定各种不同的线程属性。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个万能指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg的参数传入。
参数
第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数。
传参数
1.传多个参数:封装成结构体
typedef struct args{
int id;
char * name;
} ARGS;
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "log.h"
#include "test.h"
int * thread(void * arg)
{
pthread_t newthid;
ARGS *args = (ARGS *)arg;
newthid = pthread_self();
LOGI(LOG_TAG,"this is a new thread, args->id = %d\n", args->id);
LOGI(LOG_TAG,"this is a new thread, args->name = %s\n", args->name);
return 0;
}
int main(void)
{
pthread_t thid;
LOGI(LOG_TAG,"main thread ,ID is %ld\n",pthread_self());
ARGS *args;
args->id = 10;
args->name ="test";
//int j=10;
if(pthread_create(&thid, NULL, thread, args) != 0) {
LOGI(LOG_TAG,"thread creation failed\n");
}
}
I/jniTest: this is a new thread, args->id = 10
I/jniTest: this is a new thread, args->name = test
2.传单个参数
int * thread(void * arg)
{
pthread_t newthid;
newthid = pthread_self();
int j = (int *)arg;
LOGI(LOG_TAG,"this is a new thread, j = %d\n", j);
return 0;
}
int main(void)
{
pthread_t thid;
LOGI(LOG_TAG,"main thread ,ID is %ld\n",pthread_self());
int j=10;
if(pthread_create(&thid, NULL, thread, j) != 0) {
LOGI(LOG_TAG,"thread creation failed\n");
}
}
int * thread(void * arg)
{
pthread_t newthid;
newthid = pthread_self();
char* j = (char *)arg;
LOGI(LOG_TAG,"this is a new thread, j = %s\n", j);
return 0;
}
int main(void)
{
pthread_t thid;
LOGI(LOG_TAG,"main thread ,ID is %ld\n",pthread_self());
char *j="10";
if(pthread_create(&thid, NULL, thread, j) != 0) {
LOGI(LOG_TAG,"thread creation failed\n");
}
}
3.不传参数
pthread_create(&thid, NULL, thread, NULL)