POSIX 线程编程指南(三)

19 篇文章 3 订阅

合并与分离线程

  例程:

 合并:

  • “Joining” 是完成线程间同步的一种方式. 比如:

    Joining

  • pthread_join()会阻塞调用线程,直到指定的线程终止.

  • 如果retval不为NULL,pthread_join()会将目标线程的退出状态(即目标线程提供给pthread_exit()的值)copy到retval指向的位置.

  • 对同一线程多次调用join是逻辑错误.

  • 另外两种同步方法, 互斥体和 条件变量将稍候讨论
.

 是否可合并?

  • 当线程被创建后,它的一个属性定义了它是“joinable”还是“detached”。只有被创建为“joinable”的线程才能被合并(join)。如果线程被创建为分离的(detached),那么它永不会被合并

  • POSIX 标准的最后草案指定创建线程时应为可合并的.

  • 需要使用pthread_create() 的参数attr来显式的创建可合并或者分离的线程. 典型的四个步骤:
    1. 以pthread_attr_t 数据类型声明一个pthread属性变量
    2. 使用pthread_attr_init()初始化这个属性变量
    3. 使用pthread_attr_setdetachstate()设置属性的分离状态
    4. 完事后使用pthread_attr_destroy()释放属性使用的库资源
  分离:
  • 使用pthread_detach() 显式的将线程设置为分离的,及时它被创建为可合并的.

  • 无法逆向

 建议:

  • 如果线程需要合并,那就考虑显式的声明它。防止某些实现在创建线程时默认并不是将其设置为可合并的.

  • 如果某个线程根本不需要合并,那么创建时就将其设置为分离的。这样一些系统资源能被及早释放.

Example: Pthread Joining

  • 该示例展示了如何使用join例程"等待"线程完成.
  • 由于一些实现创建线程时可能并不将其置于可合并状态, 该例中的线程都以显式的方式创建为可合并,所以稍后它们都能被合并.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS	4

void* BusyWork(void *t)
{
	int i;
	long tid;
	double result = 0.0;
	tid = (long)t;
	printf("Thread %ld starting...\n", tid);
	for (i = 0; i < 1000000; i++)
	{
		result = result + sin(i) * tan(i);
	}
	printf("Thread %ld done. Result = %e\n", tid, result);
	pthread_exit((void *)t);
}

int main(int argc, char *argv[])
{
	pthread_t thread[NUM_THREADS];
	pthread_attr_t attr;
	int rc;
	long t;
	void *status;

	/* Initialize and set thread detached attribute */
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	for (t = 0; t < NUM_THREADS; t++)
	{
		printf("Main: creating thread %ld\n", t);
		rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
		if (rc)
		{
			printf("ERROR; return code from pthread_create() is %d\n", rc);
			exit(-1);
		}
	}

	/* Free attribute and wait for the other threads */
	pthread_attr_destroy(&attr);
	for (t = 0; t < NUM_THREADS; t++)
	{
		rc = pthread_join(thread[t], &status);
		if (rc)
		{
			printf("ERROR; return code from pthread_join() is %d\n", rc);
			exit(-1);
		}
		printf("Main: completed join with thread %ld having a status of %ld\n", t, (long)status);
	}

	printf("Main: program completed. Exiting.\n");
	pthread_exit(NULL);
}

输出:

Main: creating thread 0
Main: creating thread 1
Thread 0 starting...
Main: creating thread 2
Thread 1 starting...
Main: creating thread 3
Thread 2 starting...
Thread 3 starting...
Thread 1 done. Result = -3.153838e+06
Thread 0 done. Result = -3.153838e+06
Main: completed join with thread 0 having a status of 0
Main: completed join with thread 1 having a status of 1
Thread 3 done. Result = -3.153838e+06
Thread 2 done. Result = -3.153838e+06
Main: completed join with thread 2 having a status of 2
Main: completed join with thread 3 having a status of 3
Main: program completed. Exiting.

栈控制

  Routines:

int pthread_attr_setstacksize(pthread_attr_t *attr, size_tstacksize);

intpthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize);

int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr);
intpthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackaddr);

 防止栈问题:

  • POSIX 标准并没有规定一个线程堆栈的大小。这依赖于实现而异.

  • 超出默认堆栈限制往往是很容易做到,通常的结果︰ 程序终止和/或数据损坏.

  • 安全和可移植的程序并不依赖于默认的堆栈大小,它们会显式的使用pthread_attr_setstacksize()为每个线程分配足够的栈空间.

  • 某些环境要求线程的栈必须处于特定的内存区域,应用可以使用pthread_attr_getstackaddr() 和 pthread_attr_setstackaddr()来完成.

 Some Practical Examples at LC:

  • 线程默认栈大小的差别很大.可获得的最大值也差别很大,而且可能依赖于每个节点的线程数量

  • 下面将过去和当前的架构都列出来,用来展示默认线程栈大小的巨大差别.
    Node
    Architecture
    #CPUs Memory (GB) Default Size
    (bytes)
    Intel Xeon E5-267016322,097,152
    Intel Xeon 566012242,097,152
    AMD Opteron8162,097,152
    Intel IA644833,554,432
    Intel IA32242,097,152
    IBM Power5832196,608
    IBM Power4816196,608
    IBM Power3161698,304

Example: Stack Management

  • 该示例展示了如何查询与设置线程的栈大小.
#include <pthread.h>
#include <stdio.h>
#define NTHREADS 4
#define N 1000
#define MEGEXTRA 1000000

pthread_attr_t attr;

void* dowork(void *threadid)
{
	double A[N][N];
	int i, j;
	long tid;
	size_t mystacksize;

	tid = (long)threadid;
	pthread_attr_getstacksize(&attr, &mystacksize);
	printf("Thread %ld: stack size = %li bytes \n", tid, mystacksize);
	for (i = 0; i < N; i++)
		for (j = 0; j < N; j++)
			A[i][j] = ((i * j) / 3.452) + (N - i);
	pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
	pthread_t threads[NTHREADS];
	size_t stacksize;
	int rc;
	long t;

	pthread_attr_init(&attr);
	pthread_attr_getstacksize(&attr, &stacksize);
	printf("Default stack size = %li\n", stacksize);
	stacksize = sizeof(double) * N * N + MEGEXTRA;
	printf("Amount of stack needed per thread = %li\n", stacksize);
	pthread_attr_setstacksize(&attr, stacksize);
	printf("Creating threads with stack size = %li bytes\n", stacksize);
	for (t = 0; t < NTHREADS; t++)
	{
		rc = pthread_create(&threads[t], &attr, dowork, (void *)t);
		if (rc)
		{
			printf("ERROR; return code from pthread_create() is %d\n", rc);
			exit(-1);
		}
	}
	printf("Created %ld threads.\n", t);
	pthread_exit(NULL);
}

Miscellaneous Routines

  • pthread_self 返回系统赋予调用线程的唯一ID.

  • pthread_equal 比较两个线程ID. 如果相等返回非0,否则返回0.

  • 注意:因为线程ID是隐藏对象(opaque),所以不能使用C/C++语言的逻辑运算符==来判断它们是否相同,也不能将其与其他类型数据比较.

    pthread_once (once_control, init_routine)

    int pthread_once(pthread_once_t * once_control ,void (* init_routine )(void));
    pthread_once_t
once_control = PTHREAD_ONCE_INIT
  • pthread_once 在进程中只执行 init_routine 一次. 被任何线程第一次调用时,它执行给定的 init_routine(没有参数). 后续的调用没有无效

  • init_routine routine 一般为初始化例程.

  • once_control 参数为同步控制结构体,调用前需要初始化. For example:

    pthread_once_t once_control = PTHREAD_ONCE_INIT;







1、资源项目源码均已通过严格测试验证,保证能够正常运行;、 2项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行;、 2项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值