SlideShare a Scribd company logo
CH 5.10
THREAD-SAFETY
BY :MOHAMED RAMADAN
Thread-Safety
• A block of code is thread-safe if it can be simultaneously executed by
multiple threads without causing problems.
• When you program your own functions, you know if they are safe to
be called by multiple threads or not.
• You may forget to check if system library functions used are thread-
safe.
Unsafe function: strtok()from C string.h library
Other example.
–The random number generator random in stdlib.h.
–The time conversion function localtime in time.h.
Example of using strtok()
•“Tokenize” a English text file
# Tokens are contiguous sequences of characters separated by a
white-space, a tab, or a newline.
#Example: “Welcome back”
Two tokens: “Welcome”, “back”
• Divide the input file into lines of text and assign the lines to the threads
in a round-robin fashion.
#Each thread tokenizes a line using strtok()
#Line 1 > thread 0, Line 2 > thread 1, . . . , the t th goes to thread t,
the t +1st goes to thread 0, etc.
The strtok function
• The first time it’s called,
# the string argument is the text to be tokenized (Our line of input)
# strtok caches a static pointer to string
• For subsequent calls, it returns successive tokens taken from the
cached copy#
# the first argument should be NULL.
Run the program with a single thread
• When we run the program with a single thread, it correctly tokenizes
the input stream.
Pease porridge hot.
Pease porridge cold.
Pease porridge in the pot.
Nine days old.
• It correctly tokenizes the input stream with 1 thread
Pease
porridge
hot
…
Run the program with a two threads
The second time we run it with this input, we get the following output:
Thread 0 > line 0 = Pease porridge hot.
Thread 1 > line 1 = Pease porridge cold.
Thread 0 > token 0 = Pease
Thread 1 > token 0 = Pease
Thread 0 > token 1 = porridge
Thread 1 > token 1 = cold.
Thread 0 > line 2 = Pease porridge in the pot
Thread 1 > line 3 = Nine days old.
Thread 0 > token 0 = Pease here
Thread 1 > token 0 = Nine
Thread 0 > token 1 = days
Thread 1 > token 1 = old.
What happened?
• strtok caches the input line by declaring a variable to have static
(persistent) storage class.
# Unfortunately this cached string is shared, not private.
So the strtok function is not thread-safe. If multiple threads call it
simultaneously, the output may not be correct.
“re-entrant” (thread safe) functions
• In some cases, the C standard specifies an alternate, thread-safe,
version of a function.
Thanks

More Related Content

What's hot

Zmq in context of openstack
Zmq in context of openstackZmq in context of openstack
Zmq in context of openstack
Yatin Kumbhare
 
Kick-off Project 2: Presentatie Linux
Kick-off Project 2: Presentatie LinuxKick-off Project 2: Presentatie Linux
Kick-off Project 2: Presentatie Linux
Patrick Koning
 
Config
ConfigConfig
Config
Topsportlab
 
epoll() - The I/O Hero
epoll() - The I/O Heroepoll() - The I/O Hero
epoll() - The I/O Hero
Mohsin Hijazee
 
Blocks, procs && lambdas
Blocks, procs && lambdasBlocks, procs && lambdas
Blocks, procs && lambdas
Vidmantas Kabošis
 
Who Broke My Crypto
Who Broke My CryptoWho Broke My Crypto
Who Broke My Crypto
John Varghese
 
Kickstart Kotlin
Kickstart KotlinKickstart Kotlin
Kickstart Kotlin
Zahidur Rahman Faisal
 
memcached Binary Protocol in a Nutshell
memcached Binary Protocol in a Nutshellmemcached Binary Protocol in a Nutshell
memcached Binary Protocol in a Nutshell
Toru Maesaka
 
Nmap not only a port scanner by ravi rajput comexpo security awareness meet
Nmap not only a port scanner by ravi rajput comexpo security awareness meet Nmap not only a port scanner by ravi rajput comexpo security awareness meet
Nmap not only a port scanner by ravi rajput comexpo security awareness meet
Ravi Rajput
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
Sagiv Ofek
 
Ruby basics || updated
Ruby basics || updatedRuby basics || updated
Ruby basics || updated
datt30
 
Figure 1
Figure 1Figure 1
Figure 1
Sueng-Yong Park
 
Border Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perlBorder Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perl
David Morel
 
Creating qmgr and allowing remote authorization
Creating qmgr and allowing remote authorizationCreating qmgr and allowing remote authorization
Creating qmgr and allowing remote authorization
Ravi Babu
 
Vimm
VimmVimm
182
182182
Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018
Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018
Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018
Codemotion
 
MOVED: The challenge of SVE in QEMU - SFO17-103
MOVED: The challenge of SVE in QEMU - SFO17-103MOVED: The challenge of SVE in QEMU - SFO17-103
MOVED: The challenge of SVE in QEMU - SFO17-103
Linaro
 
Tips on High Performance Server Programming
Tips on High Performance Server ProgrammingTips on High Performance Server Programming
Tips on High Performance Server Programming
Joshua Zhu
 
Building real-time apps with WebSockets
Building real-time apps with WebSocketsBuilding real-time apps with WebSockets
Building real-time apps with WebSockets
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 

What's hot (20)

Zmq in context of openstack
Zmq in context of openstackZmq in context of openstack
Zmq in context of openstack
 
Kick-off Project 2: Presentatie Linux
Kick-off Project 2: Presentatie LinuxKick-off Project 2: Presentatie Linux
Kick-off Project 2: Presentatie Linux
 
Config
ConfigConfig
Config
 
epoll() - The I/O Hero
epoll() - The I/O Heroepoll() - The I/O Hero
epoll() - The I/O Hero
 
Blocks, procs && lambdas
Blocks, procs && lambdasBlocks, procs && lambdas
Blocks, procs && lambdas
 
Who Broke My Crypto
Who Broke My CryptoWho Broke My Crypto
Who Broke My Crypto
 
Kickstart Kotlin
Kickstart KotlinKickstart Kotlin
Kickstart Kotlin
 
memcached Binary Protocol in a Nutshell
memcached Binary Protocol in a Nutshellmemcached Binary Protocol in a Nutshell
memcached Binary Protocol in a Nutshell
 
Nmap not only a port scanner by ravi rajput comexpo security awareness meet
Nmap not only a port scanner by ravi rajput comexpo security awareness meet Nmap not only a port scanner by ravi rajput comexpo security awareness meet
Nmap not only a port scanner by ravi rajput comexpo security awareness meet
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
 
Ruby basics || updated
Ruby basics || updatedRuby basics || updated
Ruby basics || updated
 
Figure 1
Figure 1Figure 1
Figure 1
 
Border Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perlBorder Patrol - Count, throttle, kick & ban in perl
Border Patrol - Count, throttle, kick & ban in perl
 
Creating qmgr and allowing remote authorization
Creating qmgr and allowing remote authorizationCreating qmgr and allowing remote authorization
Creating qmgr and allowing remote authorization
 
Vimm
VimmVimm
Vimm
 
182
182182
182
 
Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018
Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018
Gabriele Santomaggio - Inside Elixir/Erlang - Codemotion Milan 2018
 
MOVED: The challenge of SVE in QEMU - SFO17-103
MOVED: The challenge of SVE in QEMU - SFO17-103MOVED: The challenge of SVE in QEMU - SFO17-103
MOVED: The challenge of SVE in QEMU - SFO17-103
 
Tips on High Performance Server Programming
Tips on High Performance Server ProgrammingTips on High Performance Server Programming
Tips on High Performance Server Programming
 
Building real-time apps with WebSockets
Building real-time apps with WebSocketsBuilding real-time apps with WebSockets
Building real-time apps with WebSockets
 

Similar to Thread safety

Multiprocessing with python
Multiprocessing with pythonMultiprocessing with python
Multiprocessing with python
Patrick Vergain
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
José Héctor Gálvez
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
rchakra
 
Ruby thread safety first
Ruby thread safety firstRuby thread safety first
Ruby thread safety first
Emily Stolfo
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
Dataconomy Media
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Thread 1
Thread 1Thread 1
Thread 1
RAVI MAURYA
 
Testing multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsTesting multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problems
Vassil Popovski
 
Memory model
Memory modelMemory model
Memory model
MingdongLiao
 
Parallel Programming: Beyond the Critical Section
Parallel Programming: Beyond the Critical SectionParallel Programming: Beyond the Critical Section
Parallel Programming: Beyond the Critical Section
Tony Albrecht
 
opt-mem-trx
opt-mem-trxopt-mem-trx
opt-mem-trx
Miguel Gamboa
 
tick cross game
tick cross gametick cross game
tick cross game
sanobersheir
 
CSCI  132  Practical  Unix  and  Programming   .docx
CSCI  132  Practical  Unix  and  Programming   .docxCSCI  132  Practical  Unix  and  Programming   .docx
CSCI  132  Practical  Unix  and  Programming   .docx
mydrynan
 
Lockless Programming GDC 09
Lockless Programming GDC 09Lockless Programming GDC 09
Lockless Programming GDC 09
Lee Hanxue
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
Łukasz Koniecki
 
Lecture8
Lecture8Lecture8
Lecture8
tt_aljobory
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrency
Mosky Liu
 
Lockless
LocklessLockless
Lockless
Sandeep Joshi
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
Charles Nutter
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 

Similar to Thread safety (20)

Multiprocessing with python
Multiprocessing with pythonMultiprocessing with python
Multiprocessing with python
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Ruby thread safety first
Ruby thread safety firstRuby thread safety first
Ruby thread safety first
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
 
Thread 1
Thread 1Thread 1
Thread 1
 
Testing multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsTesting multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problems
 
Memory model
Memory modelMemory model
Memory model
 
Parallel Programming: Beyond the Critical Section
Parallel Programming: Beyond the Critical SectionParallel Programming: Beyond the Critical Section
Parallel Programming: Beyond the Critical Section
 
opt-mem-trx
opt-mem-trxopt-mem-trx
opt-mem-trx
 
tick cross game
tick cross gametick cross game
tick cross game
 
CSCI  132  Practical  Unix  and  Programming   .docx
CSCI  132  Practical  Unix  and  Programming   .docxCSCI  132  Practical  Unix  and  Programming   .docx
CSCI  132  Practical  Unix  and  Programming   .docx
 
Lockless Programming GDC 09
Lockless Programming GDC 09Lockless Programming GDC 09
Lockless Programming GDC 09
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Lecture8
Lecture8Lecture8
Lecture8
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrency
 
Lockless
LocklessLockless
Lockless
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
 

Recently uploaded

Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
flufftailshop
 

Recently uploaded (20)

Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
 

Thread safety

  • 2. Thread-Safety • A block of code is thread-safe if it can be simultaneously executed by multiple threads without causing problems. • When you program your own functions, you know if they are safe to be called by multiple threads or not. • You may forget to check if system library functions used are thread- safe. Unsafe function: strtok()from C string.h library Other example. –The random number generator random in stdlib.h. –The time conversion function localtime in time.h.
  • 3. Example of using strtok() •“Tokenize” a English text file # Tokens are contiguous sequences of characters separated by a white-space, a tab, or a newline. #Example: “Welcome back” Two tokens: “Welcome”, “back” • Divide the input file into lines of text and assign the lines to the threads in a round-robin fashion. #Each thread tokenizes a line using strtok() #Line 1 > thread 0, Line 2 > thread 1, . . . , the t th goes to thread t, the t +1st goes to thread 0, etc.
  • 4. The strtok function • The first time it’s called, # the string argument is the text to be tokenized (Our line of input) # strtok caches a static pointer to string • For subsequent calls, it returns successive tokens taken from the cached copy# # the first argument should be NULL.
  • 5.
  • 6. Run the program with a single thread • When we run the program with a single thread, it correctly tokenizes the input stream. Pease porridge hot. Pease porridge cold. Pease porridge in the pot. Nine days old. • It correctly tokenizes the input stream with 1 thread Pease porridge hot …
  • 7. Run the program with a two threads The second time we run it with this input, we get the following output: Thread 0 > line 0 = Pease porridge hot. Thread 1 > line 1 = Pease porridge cold. Thread 0 > token 0 = Pease Thread 1 > token 0 = Pease Thread 0 > token 1 = porridge Thread 1 > token 1 = cold. Thread 0 > line 2 = Pease porridge in the pot Thread 1 > line 3 = Nine days old. Thread 0 > token 0 = Pease here Thread 1 > token 0 = Nine Thread 0 > token 1 = days Thread 1 > token 1 = old.
  • 8. What happened? • strtok caches the input line by declaring a variable to have static (persistent) storage class. # Unfortunately this cached string is shared, not private. So the strtok function is not thread-safe. If multiple threads call it simultaneously, the output may not be correct.
  • 9. “re-entrant” (thread safe) functions • In some cases, the C standard specifies an alternate, thread-safe, version of a function.