sliver__

4.4 Thread Libraries 본문

CS/운영체제

4.4 Thread Libraries

sliver__ 2023. 11. 9. 20:59
728x90

Two primary ways of implementing thread library.

1) The first approach is to provide a library entirely in user space with no kernel support.

2) The second approach is to implement a kernel-level library supported 
directly by the operating system.

 

Two general strategies for creating multiple threads

1) asynchronous threading : With asynchronous threading, once the parent creates a child thread, the parent resumes its execution, so that the parent and child execute concurrently and independently of one another.

There is typically little data sharing between parent and children.


2) synchronous threading : Synchronous threading occurs when the parent thread creates one or more  children and then must wait for all of its children to terminate before it resumes. Typically, synchronous threading involves significant data sharing among threads

 

Pthreads

Pthreads refers to the POSIX standard (IEEE 1003.1c) defining an API for thread creation and synchronization. This is a specification for thread behavior, not an implementation.

 

 

#include    <pthread.h> 
#include    <stdio.h>
#include    <stdlib.h>
int    sum;    /*    this    data    is    shared    by    the    thread(s)    */
void* runner(void* param);    /*    threads    call    this    function    */
int    main(int    argc, char* argv[])
{
	pthread   t    tid;    /*    the    thread    identifier    */
	pthread   attr  t    attr;    /*    set    of    thread    attributes    */
	/*    set    the    default    attributes    of    the    thread    */
	pthread attr init(&attr);
	/*    create    the    thread    */
	pthread create(&tid, &attr, runner, argv[1]);
	/*    wait    for    the    thread    to    exit    */
	pthread join(tid, NULL);
	printf("sum    =    %d∖n", sum);
}


/*    The    thread    will    execute    in    this    function    */
void* runner(void* param)
{
	int    i, upper = atoi(param);
	sum = 0;
	for (i = 1; i <= upper; i++)
		sum += i;
	pthread exit(0);
}

This program follows the thread create/join  strategy, whereby after creating the summation thread, the parent thread will wait for it to terminate by calling the pthread join() function.


Below is pthread code for joining ten threads.

#define    NUM  THREADS    10

/*    an    array    of    threads    to    be    joined    upon    */ 

pthread  t    workers[NUM  THREADS];
for    (int    i    =    0;    i    <    NUM   THREADS;    i++) 
	pthread join(workers[i],    NULL);
728x90

'CS > 운영체제' 카테고리의 다른 글

4.6 Threading Issues  (0) 2023.11.13
4.5 Implicit Threading  (0) 2023.11.13
4.2 Multicore Programming  (0) 2023.11.08
4.1 Thread & Concurrency overview  (0) 2023.11.06
3.8 Communication in Client–Server Systems  (0) 2023.11.06
Comments