#include
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
Compile and link with -pthread. //编译时需要链接pthread库
例如:gcc pthread_create.c -lpthtread
参数:
thread --- 线程ID
attr --- 线程属性,一般为NULL
start_routine --- 线程执行函数
arg --- 向start_routine传参的参数
返回值:
成功:0
失败:错误码
#include
#include
#include
#include
void *thread_func(void *arg)
{
//printf("arg: %s\n", (char *)arg);
printf("arg: %d\n", (int)arg);
while (1)
{
printf("threading\n");
sleep(1);
}
pthread_exit(NULL); //退出线程
}
int main(int argc, char *argv[])
{
char buf[100] = "hello world";
int num = 100;
int err;
pthread_t thread;
//err = pthread_create(&thread, NULL, thread_func, buf);
err = pthread_create(&thread, NULL, thread_func, (void *)num);//创建线程
if (err != 0)
{
fprintf(stderr, "pthread_create: %s\n", strerror(err));
return -1;
}
sleep(1);
pthread_cancel(thread); //取消线程
while (1)
{
printf("main........\n");
sleep(1);
}
return 0;
}