SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
Perl Programming
                 Course
            Processes and threads




Krassimir Berov

I-can.eu
Contents
1. What is a process
2. What is a thread
3. Comparison
4. Threads
   • Threaded Program Models
   • Creating and identifying Threads
   • Thread Management
   • Sharing Data
   • Synchronization and control
Contents
5. Processes
  • fork
  • pipe
  • open
  • ...
What is a process
• process
  • An instance of a running program
  • Two or more separate processes could be
    running the same program independently
    at the same time
  • A computer program itself is just a
    passive collection of instructions, while a
    process is the actual execution of those
    instructions
What is a thread
• thread
  • a thread is a flow of control through a program
    with a single execution point
  • there can be several threads of execution within
    a process
  • multiple threads share the same program code,
    operating system resources and operating
    system permissions as the process they belong
    to
Comparison
• Thread versus process
Comparison
• Processes
  • run independently and do not share
    resources
  • the fork() system call in UNIX causes creation
    of a new process
  • on Windows it is emulated by using threads
  • The return value from fork() is used to
    distinguish the parent from the child
  • the parent receives the child's process id, but
    the child receives zero
Comparison
• Processes                                          (2)
  • The new process (child process) is an exact
    copy of the calling process (parent process)
    except for the following:
    • The child process has a unique process ID
    • The child process has a different parent process
      ID (i.e., the process ID of the parent process)
    • The child process has its own copy of the parent's
      descriptors
Comparison
• Threads
  • A thread is an entity within a process that
    consists of the schedulable part of the
    process
  • Creating new threads is faster
  • Thread creation induces a peer
    relationship between all the threads of a
    process
Comparison
• Threads                           (2)

  • All threads can share
    • the parent process ID
    • the process memory
    • the process data
    • the process permissions
    • the Table with opened files
Comparison
• Threads                           (2)

  • Every thread has its own
    • thread ID
    • separate point of execution
    • thread-local storage
Threaded Program Models
• Three basic ways that you can structure a
  threaded program
  • Boss/Worker – one boss thread and one or more
    worker threads
  • Work Crew – several threads are created that do
    essentially the same thing to different pieces of
    data
  • Pipeline – a task is divided into a series of steps
     • the results of one step are passed to the thread
       processing the next step
     • Each thread does one thing to each piece of data
Creating
               and identifying Threads
• Example
 #threads_create.pl
 BEGIN {
      use Config;
      $Config{useithreads}
          or die('Threads support needed.');
 }
 use strict;use warnings;
 use threads;
 $|++;
 while (1){
      sleep 1;
      my $thread_id = threads->self()->tid;
      threads->create(&a_thread,$thread_id,[localtime]);
      #OR
      threads->new(&a_thread,$thread_id,[localtime]);
 }
 #...
Thread Management
• Waiting For A Thread To Exit
  • join
     • waits for a thread to exit,
     • cleans up after it,
     • returns any data the thread may have produced

 #threads_management.pl
 while ($i<30){
      sleep 1;
      my $odd = threads->create(&a_thread,[localtime]);
      print $odd->join(),$/;
      my $even = threads->new(&a_thread,[localtime]);
      print $even->join(),$/;
      $i++;
 }
 #...
Thread Management
• Ignoring A Thread
  • detach
     •   the thread runs until it's finished
     •   Perl will clean up after it automatically
     •   may not be joined
     •   any return data is lost
 #threads_management2.pl
 while ($i<30){
      sleep 1;
      my $odd = threads->create(&a_thread,[localtime]);
      $odd->detach();
      my $even = threads->new(&a_thread,[localtime]);
      $even->detach();
      $i++;
 }
 #...
Thread Management
• Process and Thread Termination
  • an action that terminates a process will
    terminate all running threads.
  • perl does an exit() when the main thread exits
 #threads_management3.pl
 my @threads = ();
 while ($i<30){
      push @threads, threads->new(&a_thread,[localtime]);
      push @threads, threads->new(&a_thread,[localtime]);
      $i++;
 }
 #uncomment and run again
 #print $_->join foreach @threads;
 #...
Sharing Data
• by default, no data is shared
• all the data associated with the current thread is
  copied to the new thread, and is subsequently
  private to that new thread
• all happens within the current process
  #sharing_data.pl
  my @threads = ();
  while ($i<30){
       push @threads, threads->new(&a_thread,[localtime]);
       push @threads, threads->new(&a_thread,[localtime]);
       $i++;
  }
  #uncomment and run again
  #print $_->join foreach @threads;
  #...
Sharing Data
• by default, no data is shared
• all the data associated with the current thread is
  copied to the new thread, and is subsequently
  private to that new thread
• all happens within the current process
• use threads::shared and the :shared attribute
  to share data
• only simple values or references to shared
  variables are allowed
Sharing Data
•Race conditions
  ●   caused by unsynchronized access to shared
      data
  ●   there's no way to be sure that nothing has
      happened to the shared data between the time
      you access it and the time you update it
  ●   $a += 5 or $a++ are not guaranteed to be
      atomic
Synchronization and control
• lock
  • takes a shared variable and puts a lock on it
  • no other thread may lock the variable until the
    variable is unlocked by the thread holding the lock
  • Unlocking happens automatically when the locking
    thread exits the block that contains the call to the
    lock() function
  • blocks the thread until the variable being locked is
    available
  • your thread can be sure that no other thread can lock
    that variable until the block containing the lock exits
  • does not prevent access to the variable, only lock
    attempts
Synchronization and control
• lock – Example
 #deadlock.pl
 use threads; use threads::shared;
 my $a :shared = 4;
 my $b :shared = 'foo';
 my $thr1 = threads->create(sub {
     lock($a);
     sleep(2);
     lock($b);
     $a++; $b .= $a;
 })->join ;
 my $thr2 = threads->create(sub {
     lock($b);
     sleep(2);
     lock($a);
     $a++; $b .= $a;
 })->join ;
 print $thr1,$/,$thr2,$/;
Synchronization and control

• Queues
 • A queue is a special thread-safe object
   that lets you put data in one end and take
   it out the other without having to worry
   about synchronization issues
 • add lists of scalars onto the end with
   enqueue()
 • pop scalars off the front of it with
   dequeue()
Synchronization and control

• Semaphores
 • generic locking mechanism
 • behave very much like lockable scalars,
   except that they can't hold data
 • must be explicitly unlocked
 • by default, semaphores behave like locks
 • see also: perlthrtut/Advanced Semaphores
Processes
• fork
  Does a fork(2) system call to create a new
  process running the same program at the same
  point
  • returns the child pid to the parent process, 0 to the
    child process, or undef if the fork is unsuccessful
  • file descriptors are shared, while everything else is
    copied
  • beginning with v5.6.0, Perl will attempt to flush all
    files opened for output before forking the child
    process
Processes
• fork – Example
 #io-socket-tcp-server-fork.pl
 #...
 sub REAPER {
      1 until (-1 == waitpid(-1, WNOHANG));
      $SIG{CHLD} = &REAPER;
 }
 $SIG{CHLD} = &REAPER;

 print "Server ($0) running on port $port...n";
 while (my $connection = $server->accept) {
     if (my $pid = fork){
         handle_connection($connection,$$);
     }
 }
 $server->close();
IPC
• pipe READHANDLE,WRITEHANDLE
 • Opens a pair of connected pipes like the
   corresponding system call.
 • Perl's pipes use IO buffering, so you may need to set
   $| to flush your WRITEHANDLE after each command,
   depending on the application.

 pipe (READ, WRITE);
 select WRITE;
 $| = 1;
 #...
IPC
• system PROGRAM LIST
  • exactly the same thing as exec LIST , except
    that a fork is done first, and the parent
    process waits for the child process to
    complete
  • The return value is the exit status of the
    program as returned by the wait call
  • see perlfunc/system
IPC
• open
 open(MAIL, "|/usr/lib/sendmail -oi -t")
     or die "can't fork sendmail: $!";

 print MAIL <<EOF;
 From: $0
 To: you@example.com
 Subject: blah

 EOF

 close(MAIL)
Processes and threads
• Ressources
  • Professional Perl Programming
    (Chapter 22 – Creating and Managing Processes)
  • perldoc perlthrtut
  • http://en.wikipedia.org/wiki/Process_%28computing%29
  • http://en.wikipedia.org/wiki/Thread_%28computer_science%29
  • http://gauss.ececs.uc.edu/Users/Franco/ForksThreads/forks.html

  • perldoc perlipc
  • perldoc perlfork
Processes and threads




Questions?

Más contenido relacionado

La actualidad más candente

Cpu scheduling in operating System.
Cpu scheduling in operating System.Cpu scheduling in operating System.
Cpu scheduling in operating System.Ravi Kumar Patel
 
Operating system architecture
Operating system architectureOperating system architecture
Operating system architectureSabin dumre
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Ravindra Raju Kolahalam
 
CPU Scheduling in OS Presentation
CPU Scheduling in OS  PresentationCPU Scheduling in OS  Presentation
CPU Scheduling in OS Presentationusmankiyani1
 
Operating system structures
Operating system structuresOperating system structures
Operating system structuresMohd Arif
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating SystemsRitu Ranjan Shrivastwa
 
deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidancewahab13
 
Operating Systems - "Chapter 4: Multithreaded Programming"
Operating Systems - "Chapter 4:  Multithreaded Programming"Operating Systems - "Chapter 4:  Multithreaded Programming"
Operating Systems - "Chapter 4: Multithreaded Programming"Ra'Fat Al-Msie'deen
 
Operating system memory management
Operating system memory managementOperating system memory management
Operating system memory managementrprajat007
 
CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSKathirvel Ayyaswamy
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating SystemJanki Shah
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)Prakhar Maurya
 
Operating Systems: Device Management
Operating Systems: Device ManagementOperating Systems: Device Management
Operating Systems: Device ManagementDamian T. Gordon
 

La actualidad más candente (20)

Cpu scheduling in operating System.
Cpu scheduling in operating System.Cpu scheduling in operating System.
Cpu scheduling in operating System.
 
Operating system architecture
Operating system architectureOperating system architecture
Operating system architecture
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
 
Lecture 3 threads
Lecture 3   threadsLecture 3   threads
Lecture 3 threads
 
Memory management
Memory managementMemory management
Memory management
 
process control block
process control blockprocess control block
process control block
 
CPU Scheduling in OS Presentation
CPU Scheduling in OS  PresentationCPU Scheduling in OS  Presentation
CPU Scheduling in OS Presentation
 
Deadlock Prevention
Deadlock PreventionDeadlock Prevention
Deadlock Prevention
 
Kernels and its types
Kernels and its typesKernels and its types
Kernels and its types
 
Operating system structures
Operating system structuresOperating system structures
Operating system structures
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidance
 
Operating Systems - "Chapter 4: Multithreaded Programming"
Operating Systems - "Chapter 4:  Multithreaded Programming"Operating Systems - "Chapter 4:  Multithreaded Programming"
Operating Systems - "Chapter 4: Multithreaded Programming"
 
Operating system memory management
Operating system memory managementOperating system memory management
Operating system memory management
 
Deadlock
DeadlockDeadlock
Deadlock
 
CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMS
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating System
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
Operating Systems: Device Management
Operating Systems: Device ManagementOperating Systems: Device Management
Operating Systems: Device Management
 

Destacado (9)

Processes and Processors in Distributed Systems
Processes and Processors in Distributed SystemsProcesses and Processors in Distributed Systems
Processes and Processors in Distributed Systems
 
Process of operating system
Process of operating systemProcess of operating system
Process of operating system
 
Os presentation process
Os presentation processOs presentation process
Os presentation process
 
Process in operating system
Process in operating systemProcess in operating system
Process in operating system
 
Chapter 3 - Processes
Chapter 3 - ProcessesChapter 3 - Processes
Chapter 3 - Processes
 
Lecture 5 process concept
Lecture 5   process conceptLecture 5   process concept
Lecture 5 process concept
 
Processes Control Block (Operating System)
Processes Control Block (Operating System)Processes Control Block (Operating System)
Processes Control Block (Operating System)
 
Process management
Process managementProcess management
Process management
 
Introduction to Computers
Introduction to ComputersIntroduction to Computers
Introduction to Computers
 

Similar a Perl Programming Course - Processes and Threads

Course 102: Lecture 18: Process Life Cycle
Course 102: Lecture 18: Process Life CycleCourse 102: Lecture 18: Process Life Cycle
Course 102: Lecture 18: Process Life CycleAhmed El-Arabawy
 
Threads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationThreads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationShivam Mitra
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreadingssusere538f7
 
Cutting Back Processing Time
Cutting Back Processing TimeCutting Back Processing Time
Cutting Back Processing TimeHenrique Moody
 
Operating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - ThreadsOperating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - ThreadsPeter Tröger
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptxLECO9
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptxSKUP1
 
Multithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfMultithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfHarika Pudugosula
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxSaiDhanushM
 
Chapter -2 operating system presentation
Chapter -2 operating system presentationChapter -2 operating system presentation
Chapter -2 operating system presentationchnrketan
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Charles Nutter
 

Similar a Perl Programming Course - Processes and Threads (20)

MULTI THREADING.pptx
MULTI THREADING.pptxMULTI THREADING.pptx
MULTI THREADING.pptx
 
Course 102: Lecture 18: Process Life Cycle
Course 102: Lecture 18: Process Life CycleCourse 102: Lecture 18: Process Life Cycle
Course 102: Lecture 18: Process Life Cycle
 
Threads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationThreads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess Communication
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Cutting Back Processing Time
Cutting Back Processing TimeCutting Back Processing Time
Cutting Back Processing Time
 
Operating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - ThreadsOperating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - Threads
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptx
 
Processes, Threads.pptx
Processes, Threads.pptxProcesses, Threads.pptx
Processes, Threads.pptx
 
Multithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfMultithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdf
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
 
Chapter -2 operating system presentation
Chapter -2 operating system presentationChapter -2 operating system presentation
Chapter -2 operating system presentation
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Java
JavaJava
Java
 
Java threads
Java threadsJava threads
Java threads
 
Multithreading
MultithreadingMultithreading
Multithreading
 
multithreading
multithreadingmultithreading
multithreading
 
Java
JavaJava
Java
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014
 

Más de Krasimir Berov (Красимир Беров) (14)

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в Perl
Въведение в PerlВъведение в Perl
Въведение в Perl
 
Network programming
Network programmingNetwork programming
Network programming
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Subroutines
SubroutinesSubroutines
Subroutines
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Syntax
SyntaxSyntax
Syntax
 
Hashes
HashesHashes
Hashes
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Perl Programming Course - Processes and Threads

  • 1. Perl Programming Course Processes and threads Krassimir Berov I-can.eu
  • 2. Contents 1. What is a process 2. What is a thread 3. Comparison 4. Threads • Threaded Program Models • Creating and identifying Threads • Thread Management • Sharing Data • Synchronization and control
  • 3. Contents 5. Processes • fork • pipe • open • ...
  • 4. What is a process • process • An instance of a running program • Two or more separate processes could be running the same program independently at the same time • A computer program itself is just a passive collection of instructions, while a process is the actual execution of those instructions
  • 5. What is a thread • thread • a thread is a flow of control through a program with a single execution point • there can be several threads of execution within a process • multiple threads share the same program code, operating system resources and operating system permissions as the process they belong to
  • 7. Comparison • Processes • run independently and do not share resources • the fork() system call in UNIX causes creation of a new process • on Windows it is emulated by using threads • The return value from fork() is used to distinguish the parent from the child • the parent receives the child's process id, but the child receives zero
  • 8. Comparison • Processes (2) • The new process (child process) is an exact copy of the calling process (parent process) except for the following: • The child process has a unique process ID • The child process has a different parent process ID (i.e., the process ID of the parent process) • The child process has its own copy of the parent's descriptors
  • 9. Comparison • Threads • A thread is an entity within a process that consists of the schedulable part of the process • Creating new threads is faster • Thread creation induces a peer relationship between all the threads of a process
  • 10. Comparison • Threads (2) • All threads can share • the parent process ID • the process memory • the process data • the process permissions • the Table with opened files
  • 11. Comparison • Threads (2) • Every thread has its own • thread ID • separate point of execution • thread-local storage
  • 12. Threaded Program Models • Three basic ways that you can structure a threaded program • Boss/Worker – one boss thread and one or more worker threads • Work Crew – several threads are created that do essentially the same thing to different pieces of data • Pipeline – a task is divided into a series of steps • the results of one step are passed to the thread processing the next step • Each thread does one thing to each piece of data
  • 13. Creating and identifying Threads • Example #threads_create.pl BEGIN { use Config; $Config{useithreads} or die('Threads support needed.'); } use strict;use warnings; use threads; $|++; while (1){ sleep 1; my $thread_id = threads->self()->tid; threads->create(&a_thread,$thread_id,[localtime]); #OR threads->new(&a_thread,$thread_id,[localtime]); } #...
  • 14. Thread Management • Waiting For A Thread To Exit • join • waits for a thread to exit, • cleans up after it, • returns any data the thread may have produced #threads_management.pl while ($i<30){ sleep 1; my $odd = threads->create(&a_thread,[localtime]); print $odd->join(),$/; my $even = threads->new(&a_thread,[localtime]); print $even->join(),$/; $i++; } #...
  • 15. Thread Management • Ignoring A Thread • detach • the thread runs until it's finished • Perl will clean up after it automatically • may not be joined • any return data is lost #threads_management2.pl while ($i<30){ sleep 1; my $odd = threads->create(&a_thread,[localtime]); $odd->detach(); my $even = threads->new(&a_thread,[localtime]); $even->detach(); $i++; } #...
  • 16. Thread Management • Process and Thread Termination • an action that terminates a process will terminate all running threads. • perl does an exit() when the main thread exits #threads_management3.pl my @threads = (); while ($i<30){ push @threads, threads->new(&a_thread,[localtime]); push @threads, threads->new(&a_thread,[localtime]); $i++; } #uncomment and run again #print $_->join foreach @threads; #...
  • 17. Sharing Data • by default, no data is shared • all the data associated with the current thread is copied to the new thread, and is subsequently private to that new thread • all happens within the current process #sharing_data.pl my @threads = (); while ($i<30){ push @threads, threads->new(&a_thread,[localtime]); push @threads, threads->new(&a_thread,[localtime]); $i++; } #uncomment and run again #print $_->join foreach @threads; #...
  • 18. Sharing Data • by default, no data is shared • all the data associated with the current thread is copied to the new thread, and is subsequently private to that new thread • all happens within the current process • use threads::shared and the :shared attribute to share data • only simple values or references to shared variables are allowed
  • 19. Sharing Data •Race conditions ● caused by unsynchronized access to shared data ● there's no way to be sure that nothing has happened to the shared data between the time you access it and the time you update it ● $a += 5 or $a++ are not guaranteed to be atomic
  • 20. Synchronization and control • lock • takes a shared variable and puts a lock on it • no other thread may lock the variable until the variable is unlocked by the thread holding the lock • Unlocking happens automatically when the locking thread exits the block that contains the call to the lock() function • blocks the thread until the variable being locked is available • your thread can be sure that no other thread can lock that variable until the block containing the lock exits • does not prevent access to the variable, only lock attempts
  • 21. Synchronization and control • lock – Example #deadlock.pl use threads; use threads::shared; my $a :shared = 4; my $b :shared = 'foo'; my $thr1 = threads->create(sub { lock($a); sleep(2); lock($b); $a++; $b .= $a; })->join ; my $thr2 = threads->create(sub { lock($b); sleep(2); lock($a); $a++; $b .= $a; })->join ; print $thr1,$/,$thr2,$/;
  • 22. Synchronization and control • Queues • A queue is a special thread-safe object that lets you put data in one end and take it out the other without having to worry about synchronization issues • add lists of scalars onto the end with enqueue() • pop scalars off the front of it with dequeue()
  • 23. Synchronization and control • Semaphores • generic locking mechanism • behave very much like lockable scalars, except that they can't hold data • must be explicitly unlocked • by default, semaphores behave like locks • see also: perlthrtut/Advanced Semaphores
  • 24. Processes • fork Does a fork(2) system call to create a new process running the same program at the same point • returns the child pid to the parent process, 0 to the child process, or undef if the fork is unsuccessful • file descriptors are shared, while everything else is copied • beginning with v5.6.0, Perl will attempt to flush all files opened for output before forking the child process
  • 25. Processes • fork – Example #io-socket-tcp-server-fork.pl #... sub REAPER { 1 until (-1 == waitpid(-1, WNOHANG)); $SIG{CHLD} = &REAPER; } $SIG{CHLD} = &REAPER; print "Server ($0) running on port $port...n"; while (my $connection = $server->accept) { if (my $pid = fork){ handle_connection($connection,$$); } } $server->close();
  • 26. IPC • pipe READHANDLE,WRITEHANDLE • Opens a pair of connected pipes like the corresponding system call. • Perl's pipes use IO buffering, so you may need to set $| to flush your WRITEHANDLE after each command, depending on the application. pipe (READ, WRITE); select WRITE; $| = 1; #...
  • 27. IPC • system PROGRAM LIST • exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete • The return value is the exit status of the program as returned by the wait call • see perlfunc/system
  • 28. IPC • open open(MAIL, "|/usr/lib/sendmail -oi -t") or die "can't fork sendmail: $!"; print MAIL <<EOF; From: $0 To: you@example.com Subject: blah EOF close(MAIL)
  • 29. Processes and threads • Ressources • Professional Perl Programming (Chapter 22 – Creating and Managing Processes) • perldoc perlthrtut • http://en.wikipedia.org/wiki/Process_%28computing%29 • http://en.wikipedia.org/wiki/Thread_%28computer_science%29 • http://gauss.ececs.uc.edu/Users/Franco/ForksThreads/forks.html • perldoc perlipc • perldoc perlfork