linux创建线程

线程:
进程:资源分配的基本单位
线程:系统调度的基本单位
 
线程创建: pthread_create (&tid 返回子线程ID, 属性,子线程函数入口(函数指针),函数传入参数)

 sqrt  :-lm  -->  - link libm.a
 pthread:-lpthread  ->  -link libpthread.a


线程创建时候要注意属性:
优先级 、调度、分离状态(detach? joined?)、栈大小及起始地址,没有特殊要求就设成NULL
系统默认是个join线程,非分离


子线程函数入口 是有返回值void *的, 也可以传入参数,具体的参数类型是第四个参数传入

线程的回收: 只针对的是非分离线程 pthread_join


注意:  1:主线程会先继续执行;
  如果主线程没有等待回收或者其它阻塞,主线程结束的时候,整个进程也就结束了
2:如果线程中调用了exit类的函数,会直接退出整个进程;

  return  (void *)0 ; 则返回到调用的线程中。

实例:

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

int a=0;

void *myThread1(void)
{
	int i;
	for(i=0; i<3; i++)
	{
		a++;
		printf("pthread1: a=%d   ",a);
		printf("This is the 1st pthread,pid is %d;tid1=%lu\n",getpid(),pthread_self());
		sleep(1);//Let this thread to sleep 1 second,and then continue to run
		return (void *)0;// exit (0);
	}
}

void *myThread2(void)
{
	int i;
	for (i=0; i<3; i++)
	{
		a++;
		printf("pthread2: a=%d   ",a);
		printf("This is the 2st pthread,pid is %d;tid2=%lu\n",getpid(),pthread_self());
		sleep(1);
	}
}

int main()
{
	int i=0, ret=0;
	pthread_t tid1,tid2;
    
	printf("main creat thread1\n");
	ret = pthread_create(&tid1, NULL, (void*)myThread1, NULL);
	if (ret)
	{
		perror("Create pthread1 error:\n");
		return 1;
	}
	printf("main creat thread2\n");
	ret = pthread_create(&tid2, NULL,(void*) myThread2, NULL);
	if (ret)
	{
		perror("Create pthread2 error:");
		return 1; 
	}
	a++;
	printf("pthread main : a=%d  ",a);
	printf("This is main pthread,process id is %d;tid=%lu\n",getpid(),pthread_self());
	pthread_join(tid1, NULL);
	printf("tid1 end \n");
	pthread_join(tid2, NULL);
	printf("thread1&thread2 end, a=%d\n",a);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux ,可以使用以下步骤来创建线程: 1. 包含头文件:首先,需要包含 `<pthread.h>` 头文件,该头文件提供了线程相关的函数和数据类型的定义。 2. 定义线程函数:接下来,需要定义一个函数作为线程的入口点。线程函数的返回类型为 `void*`,参数为 `void*`。这个函数将在新线程执行。 3. 创建线程:使用 `pthread_create` 函数来创建线程。该函数接受四个参数:指向线程标识符的指针、线程属性、线程函数的指针和传递给线程函数的参数。 4. 等待线程结束(可选):如果需要等待线程执行完成,可以使用 `pthread_join` 函数。该函数会阻塞调用线程,直到指定的线程结束。 下面是一个简单的示例代码: ```c #include <stdio.h> #include <pthread.h> void* thread_func(void* arg) { int thread_num = *(int*)arg; printf("Hello from thread %d\n", thread_num); pthread_exit(NULL); } int main() { pthread_t thread_id; int thread_num = 1; // 创建线程 if (pthread_create(&thread_id, NULL, thread_func, &thread_num) != 0) { printf("Failed to create thread\n"); return 1; } // 等待线程结束 if (pthread_join(thread_id, NULL) != 0) { printf("Failed to join thread\n"); return 1; } printf("Thread joined\n"); return 0; } ``` 在上面的示例,我们创建了一个新线程,它将执行 `thread_func` 函数,并传递了一个整数作为参数。主线程等待新线程执行完成后,输出 "Thread joined"。请注意,这只是一个简单的示例,实际应用可能需要更复杂的线程管理和同步机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值