3. POSIX Multithreaded Programming
The original Pthreads API was defined in the ANSI/IEEE POSIX 1003.1 - 1995 standard.
Pthreads API can be informally grouped into four major groups:
Thread management: Routines that work directly on threads - creating, detaching, joining, etc.
Mutexes (mutual exclusion): Routines that deal with synchronization. Mutex functions provide for    creating, destroying, locking and unlocking mutexes.
Condition variables: Routines that address communications between threads that share a mutex.    This group includes functions to create, destroy, wait and signal based upon specified variable    values. Functions to set/query condition variable attributes are also included.
Synchronization: Routines that manage read/write locks and barriers.
– All identifiers in the threads library begin with pthread_. Some examples are shown below.
Routine Prefix
Thread management pthread_
Mutexes pthread_mutex_
Condition variables pthread_cond_
Synchronization pthread_rwlock_, pthread_barrier_
#include <pthread.h>
gcc −Wall −O0 −o <output> file.c −pthread (no −l prefix)
int pthread_create (pthread_t thread,
                                    const pthread _attr _t attr,
                                    void ∗( ∗ start _routine )( void ∗), void arg );
– creates a new thread with the attributes specified by attr.
– Default attributes are used if attr is NULL.
– On success, stores the thread it into thread
– calls function start_routine(arg) on a separate thread of execution.
– returns zero on success, non-zero on error.
void pthread_exit(void∗ value_ptr);
– called implicitly when thread function exits.
– analogous to exit().
#include <pthread.h>
#include <stdio.h>

void *ThreadProc(void *param)
    int val;
    val = (int)param;

    printf(“%d Thread is Running!\n", val);

int main()
    pthread_t threads[5];
    int i, reault;

    for(i=0; i<5; i++){
       result = pthread_create(&threads[i], NULL,
                                              ThreadProc, (void *)i);
       if (result){
         printf(“error code = %d\n", result); exit(-1);
이전페이지 / 4 / 다음페이지