24 Multi-Threading

Source: Internet
Author: User
Tags int size usleep

Basic concepts

Threads: One process process

A process can have multiple threads, and a process is the parent process of a thread

All threads share resources with parent processes

Thread classification

Kernel-State threads

Direct dispatch by the kernel scheduler to give full play to the benefits of multiprocessor

At present, the Linux system standard line libraries uses the kernel thread way realizes multithreading

User-State thread

A process consists of multiple threads, which are just a process from the point of view of the kernel scheduler, which is dispatched by the kernel as a process. Scheduling between threads is performed in the user state

User-State threading advantage is high scheduling efficiency (no need to participate in the kernel scheduling), the disadvantage is that multi-core processor utilization is not high, one thread blocking will cause the whole thread group to block

Creating Threads

#include <pthread.h>

int Pthread_create (pthread_t *id, pthread_attr_t *attr, void *pfun, void *args)

Parameters:

ID: Returns the thread ID

attr: Thread Properties

Pfun: A function called by a thread

Args: Parameters for thread functions

Note: Create successful return 0, otherwise return error code

Thread Management

Pthread_exit (void *pret) PRet The specified thread exits the return value

int Pthread_join (pthread_t id, void **pret)

Causes the main process to wait for the thread to finish before exiting

PRet gets the return value of the Pthread_exit function call, which is generally null

Pthread_self ()

Thread function, get the thread ID of this thread

PTHREAD_GETATTR_NP (pthread_t ID, pthread_attr_t *attr)

Get Thread Properties

Thread properties, calling the Init function to initialize thread properties

Pthread_attr_init (pthread_attr_t *attr)

struct pthread_attr_t {

int __detachstate;

int __schedpolicy;

struct Sched_param __schedparam;

int __inheritsched;

int __scope;

size_t __guardsize;

int __stackaddr_set;

void * __STACKADDR;

unsigned long int __stacksize;

}

Threading properties in a detailed

__detachstate: Thread Detach State

Pthread_create_joinable can be connected to other threads

Pthread_create_detached

Set/Get Thread detach state

int Pthread_attr_setdetachstate (pthread_attr_t *attr, int detachstate)

int Pthread_attr_getdetachstate (pthread_attr_t *attr, int *pdetachstate)

__schedpolicy: Thread Scheduling policy

Sched_other system default (tick scheduling), each priority task time rotation

Sched_fifo real-time scheduling, first-come-first service (exclusive)

SCHED_RR Realtime scheduling, time-slice rotation (high-priority rotation)

Set/Get Thread scheduling policy

int Pthread_attr_setschedpolicy (pthread_attr_t *attr, int policy)

int Pthread_attr_getschedpolicy (pthread_attr_t *attr, int *ppolicy)

__schedparam Thread-Priority information

__schedparam.sched_priority

Set Get thread Property parameters

int Pthread_attr_setschedparam (pthread_attr_t *attr, struct Sched_param *param)

int Pthread_attr_getschedparam (pthread_attr_t *attr, struct Sched_param *param)

For Sched_fifo SCHED_RR scheduling, set priority param.sched_priority

__inheritsched Thread Inheritance

Pthread_inherit_sched inherit schedule properties from parent process

Pthread_explicit_sched not inherit schedule properties from parent process

Set/Get Thread inheritance

int pthread_attr_setinheritsched (pthread_attr_t *attr, int inheritsched)

int pthread_attr_getinheritsched (pthread_attr_t *attr, int *pinheritsched)

__scope Thread Scope

Pthread_scope_system system all inter-process scheduling

Pthread_scope_process current inter-process scheduling

Set/Get thread scope

int Pthread_attr_setscope (pthread_attr_t *attr, int scope)

int Pthread_attr_getscope (pthread_attr_t *attr, int *pscope)

__STACKADDR Thread Stack Address

__stacksize Thread Stack size

Get/Set Thread buyers

int pthread_attr_setstackaddr (pthread_attr_t *attr, void * stackaddr)

int pthread_attr_getstackaddr (pthread_attr_t *attr, void * * stackaddr)

int Pthread_attr_setstacksize (pthread_attr_t *attr, size_t *stacksize)

int Pthread_attr_setstacksize (pthread_attr_t *attr, size_t *stacksize)

__guardsize Alert Buffer Size

Buyers end of thread to prevent buyers overflow of extended memory size

Set/Get thread alert buffer

int Pthread_attr_getguardsize (pthread_attr_t *attr, size_t *guardsize)

int Pthread_attr_setguardsize (pthread_attr_t *attr, size_t *guardsize)

Invalid thread properties

Pthread_attr_destroy (pthread_attr_t *attr)

After invalidation, creating a thread with attr will fail

Exit thread mode

1: thread specifies that the function has finished executing

2: Process exit

3: Thread calls the EXEC function

4: Thread call pthread_exit function exits

5: Thread Call Pthread_cancel terminated

Pthread_exit (void *pret) PRet The specified thread exits the return value, which can be used for pthread_join ()

Example:

#define _gnu_source

#include <stdio.h>

#include <pthread.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

int G_ret;

void* thread ()

{

printf ("My thread ID% #x \ n", (int) pthread_self ());

int i = 10;

while (i--)

{

printf ("-%d\n", i);

Usleep (1000);

}

G_ret = 100;

Pthread_exit (&g_ret);

return NULL;

}

int Create_demo ()

{

pthread_t Tid;

int iRet;

IRet = pthread_create (&tid, NULL, thread, NULL);

if (IRet)

{

Perror ("Fail to pthread_create!");

return iRet;

}

printf ("Create thread:% #x \ n", (int) tid);

int i=5;

while (i--)

{

printf ("Main--%d\n", i);

Usleep (1000);

}

Pthread_join (Tid, NULL);

int *p;

Pthread_join (Tid, (void*) &p);//p point to G_ret;

printf ("Exit code%d\n", *p);

Sleep (1);

return 0;

}

void* Threadn (void* param)

{

int n = * ((int*) param);

int iret=0;

int i;

for (i=0; i<n; i++)

{

Iret+=i;

fprintf (stderr, "thread[%d]->%d\n", N, IRet);

Usleep (100*1000);

}

printf ("\ n");

return NULL;

}

void Test_threadn ()

{

pthread_t tid1, Tid2, TID3;

int x1=20, x2=15, x3=10;

Pthread_create (&tid1, NULL, Threadn, (void*) &x1);

Pthread_create (&tid2, NULL, Threadn, (void*) &x2);

Pthread_create (&TID3, NULL, Threadn, (void*) &x3);

Pthread_join (TID1, NULL);

Pthread_join (Tid2, NULL);

Pthread_join (TID3, NULL);

Return

}

typedef struct TAGNUMARR

{

int *arr;

int size;

}n_arr;

void* largesort (void *param)

{

N_arr STARR;

memcpy (&starr, param, sizeof (N_arr));

/* Sort (Starr.arr, starr.size) */

/* Save (STARR) */

return NULL;

}

void Test_largesort ()

{

int arr[] = {1,3,5,7,9,2,4,6,8,10};

N_arr STARR = {arr, sizeof (arr)/sizeof (arr[0])};

pthread_t Tid;

Pthread_create (&tid, NULL, Largesort, (void*) &starr);

//.......

Pthread_join (Tid, NULL);

Return

}

void Print_selfattr ()

{

pthread_attr_t attr;

pthread_t tid = pthread_self ();

Pthread_getattr_np (Tid, &attr);

int idetachstate;

Pthread_attr_getdetachstate (&attr, &idetachstate);

printf ("Detach:%s\n", idetachstate = = pthread_create_detached?) Detached ":" joinable ");

Return

}

void Test_threadattr ()

{

pthread_attr_t attr;

Pthread_attr_init (&attr);//initialized thread attrib

Pthread_attr_setdetachstate (&attr, pthread_create_detached);

pthread_t Tid;

Pthread_create (&tid, &attr, (void*) print_selfattr, NULL);

Pthread_attr_destroy (&ATTR);

Pthread_join (Tid, NULL);

Return

}

int main ()

{

Create_demo ();

Test_threadn ();

Test_threadattr ();

return 0;

}

Attention:

Using Gcc–g–wall Main.c–o main will make an error.

Undefined reference to ' pthread_create '

Undefined reference to ' Pthread_join '

Collect2:error:ld returned 1 exit status

However, using gcc–g–wall-c Main.c-o MAIN.O does not make an error.

Explains that the compilation process is fine, and that there is a problem with the link process.

So

Gcc–g–wall Main.c–o Main–lpthread

-L represents a link to the Pthread library

Makefile Modification:

. Phony:clean All

src=$ (wildcard *.c)

bin=$ (src:%.c=%)

cppsrc=$ (wildcard *.cpp)

cppbin=$ (cppsrc:%.cpp=%)

cc=gcc

cxx=g++

Cflags=-g-wall

Cxxflags =-g-wall-std=c++11

all:$ (BIN) $ (cppbin)

$ (BIN):%:%.c

$ (CC) $ (CFLAGS) $^-o [email protected]-lpthread

Clean

RM-FR $ (BIN) $ (cppbin)

24 Multi-Threading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.