Share to: share facebook share twitter share wa share telegram print page

Pthreads

In computing, POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a programming language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time. Each flow of work is referred to as a thread, and creation and control over these flows is achieved by making calls to the POSIX Threads API. POSIX Threads is an API defined by the Institute of Electrical and Electronics Engineers (IEEE) standard POSIX.1c, Threads extensions (IEEE Std 1003.1c-1995).

Implementations of the API are available on many Unix-like POSIX-conformant operating systems such as FreeBSD, NetBSD, OpenBSD, Linux, macOS, Android,[1] Solaris, Redox, and AUTOSAR Adaptive, typically bundled as a library libpthread. DR-DOS and Microsoft Windows implementations also exist: within the SFU/SUA subsystem which provides a native implementation of a number of POSIX APIs, and also within third-party packages such as pthreads-w32,[2] which implements pthreads on top of existing Windows API.

Contents

pthreads defines a set of C programming language types, functions and constants. It is implemented with a pthread.h header and a thread library.

There are around 100 threads procedures, all prefixed pthread_ and they can be categorized into five groups:

The POSIX semaphore API works with POSIX threads but is not part of the threads standard, having been defined in the POSIX.1b, Real-time extensions (IEEE Std 1003.1b-1993) standard. Consequently, the semaphore procedures are prefixed by sem_ instead of pthread_.

Example

An example illustrating the use of pthreads in C:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_THREADS 5

void *perform_work(void *arguments){
  int index = *((int *)arguments);
  int sleep_time = 1 + rand() % NUM_THREADS;
  printf("Thread %d: Started.\n", index);
  printf("Thread %d: Will be sleeping for %d seconds.\n", index, sleep_time);
  sleep(sleep_time);
  printf("Thread %d: Ended.\n", index);
  return NULL;
}

int main(void) {
  pthread_t threads[NUM_THREADS];
  int thread_args[NUM_THREADS];
  int i;
  int result_code;
  
  //create all threads one by one
  for (i = 0; i < NUM_THREADS; i++) {
    printf("In main: Creating thread %d.\n", i);
    thread_args[i] = i;
    result_code = pthread_create(&threads[i], NULL, perform_work, &thread_args[i]);
    assert(!result_code);
  }

  printf("In main: All threads are created.\n");

  //wait for each thread to complete
  for (i = 0; i < NUM_THREADS; i++) {
    result_code = pthread_join(threads[i], NULL);
    assert(!result_code);
    printf("In main: Thread %d has ended.\n", i);
  }

  printf("Main program has ended.\n");
  return 0;
}

This program creates five threads, each executing the function perform_work that prints the unique number of this thread to standard output. If a programmer wanted the threads to communicate with each other, this would require defining a variable outside of the scope of any of the functions, making it a global variable. This program can be compiled using the gcc compiler with the following command:

gcc pthreads_demo.c -pthread -o pthreads_demo

Here is one of the many possible outputs from running this program.

In main: Creating thread 0.
In main: Creating thread 1.
In main: Creating thread 2.
In main: Creating thread 3.
Thread 0: Started.
In main: Creating thread 4.
Thread 3: Started.
Thread 2: Started.
Thread 0: Will be sleeping for 3 seconds.
Thread 1: Started.
Thread 1: Will be sleeping for 5 seconds.
Thread 2: Will be sleeping for 4 seconds.
Thread 4: Started.
Thread 4: Will be sleeping for 1 seconds.
In main: All threads are created.
Thread 3: Will be sleeping for 4 seconds.
Thread 4: Ended.
Thread 0: Ended.
In main: Thread 0 has ended.
Thread 2: Ended.
Thread 3: Ended.
Thread 1: Ended.
In main: Thread 1 has ended.
In main: Thread 2 has ended.
In main: Thread 3 has ended.
In main: Thread 4 has ended.
Main program has ended.

POSIX Threads for Windows

Windows does not support the pthreads standard natively, therefore the Pthreads4w project seeks to provide a portable and open-source wrapper implementation. It can also be used to port Unix software (which uses pthreads) with little or no modification to the Windows platform.[4] Pthreads4w version 3.0.0[5] or later, released under the Apache Public License v2.0, is compatible with 64-bit or 32-bit Windows systems. Version 2.11.0,[6] released under the LGPLv3 license, is also 64-bit or 32-bit compatible.

The Mingw-w64 project also contains a wrapper implementation of 'pthreads, winpthreads, which tries to use more native system calls than the Pthreads4w project.[7]

Interix environment subsystem available in the Windows Services for UNIX/Subsystem for UNIX-based Applications package provides a native port of the pthreads API, i.e. not mapped on Win32 API but built directly on the operating system syscall interface.[8]

See also

References

  1. ^ "libc/bionic/pthread.c - platform/bionic - Git at Google". android.googlesource.com.
  2. ^ "Pthread Win-32: Level of standards conformance". 2006-12-22. Archived from the original on 2010-06-11. Retrieved 2010-08-29.
  3. ^ "pthread.h(0p) — Linux manual page". Retrieved 18 December 2022.
  4. ^ Hart, Johnson M. (2004-11-21). "Experiments with the Open Source Pthreads Library and Some Comments". Archived from the original on 2010-08-30. Retrieved 2010-08-29.
  5. ^ File: pthreads4w-code-v3.0.0.zip – Source for pthreads4w v3.0.0
  6. ^ File: pthreads4w-code-v2.11.0.zip – Source for pthreads4w v2.11.0
  7. ^ see http://locklessinc.com/articles/pthreads_on_windows which is where it was originally derived from
  8. ^ "Chapter 1: Introduction to Windows Services for UNIX 3.5". 5 December 2007.

Further reading

Read other articles:

Keluarga Garuda di DadakuPoster resmiGenre Drama Keluarga Olahraga PembuatSalto Films & MNC PicturesDitulis olehSalman AristoRino SarjonoSutradara Angga Dwimas Sasongko Ifa Isfansyah Pemeran Oka Antara Revalina S. Temat Bima Azriel Ersya Aurelia Abdurrahman Arif Yusuf Mahardika Bebeto Leutualy Farhan Papilaya Baron Yusuf Muksin Penata musikAghi NarottamaNegara asalIndonesiaBahasa asliBahasa IndonesiaJmlh. musim2Jmlh. episode3 (daftar episode)ProduksiProduser eksekutif Shanty Harmayn...

Malaysia Book of Records[1] (atau MBR) adalah sebuah proyek Malaysia untuk mempublikasikan rekor-rekor yang dibuat atau dipecahkan oleh orang-orang Malaysia. Proyek tersebut dicanangkan pada mantan Perdana Menteri Tun Dr Mahathir Bin Mohamad pada kampanye 'Malaysia Boleh!' (Malaysia Bisa! dalam bahasa Indonesia).[2] Seperti halnya Guinness World Records, proyek tersebut mempublikasikan sebuah buku yang berisi daftar rekor pada setiap tahun. Catatan ^ The Malaysia Book of Recor...

Дифракция отражённых электронов (National Institute of Standards and Technology Materials Reliability Division) Дифракция отражённых электронов с монокристалла кремния Дифракция отражённых электронов (ДОЭ) — микроструктурная кристаллографическая методика, используемая для исследования кристаллогра

العصفورية معلومات الكتاب المؤلف غازي عبد الرحمن القصيبي اللغة العربية الناشر دار الساقي تاريخ النشر 2006 النوع الأدبي رواية الفريق فنان الغلاف بيكاسو المواقع ردمك 13 9781855163836 تعديل مصدري - تعديل   العصفورية هي رواية للأديب السعودي غازي عبد الرحمن القصيبي تقع في حوالي الثلا...

العلاقات السويدية الكورية الشمالية السويد كوريا الشمالية   السويد   كوريا الشمالية تعديل مصدري - تعديل   العلاقات السويدية الكورية الشمالية هي العلاقات الثنائية التي تجمع بين السويد وكوريا الشمالية.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (ديسمبر 2020) دونالد إم. فيليبس معلومات شخصية الميلاد 24 أغسطس 1929  الوفاة 13 أكتوبر 2016 (87 سنة)   مواطنة كندا  الحياة العملية المهنة سياسي  اللغات الإنجليزية  تعد...

العلاقات الجيبوتية السنغافورية جيبوتي سنغافورة   جيبوتي   سنغافورة تعديل مصدري - تعديل   العلاقات الجيبوتية السنغافورية هي العلاقات الثنائية التي تجمع بين جيبوتي وسنغافورة.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وج...

1986 video gameAsterix and the Magic CauldronDeveloper(s)Beam SoftwarePublisher(s)Melbourne HousePlatform(s)Amstrad CPC, Commodore 64, ZX SpectrumReleaseSeptember 1986Genre(s)AdventureMode(s)Single player Asterix and the Magic Cauldron is a computer game for the Amstrad CPC, Commodore 64 and ZX Spectrum home computers based on the popular French Asterix comic books. The game was released in 1986. In North America, the Commodore 64 version was released as Ardok the Barbarian, without the Aster...

Egyptian American journalist and reporter (born 1977) This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Hannah Allam – news · newspapers · books · scholar · JSTOR (November 2014) (Learn how and wh...

Station of the Berlin U-Bahn HellersdorfPlatform view of HellersdorfGeneral informationLocationRiesaer Straße/Hellersdorfer StraßeBerlin, HellersdorfGermanyOwned byBerliner VerkehrsbetriebeOperated byBerliner VerkehrsbetriebePlatforms1 island platformTracks2Train operatorsBerliner VerkehrsbetriebeConnections X54 195ConstructionStructure typeAbove groundOther informationFare zoneVBB: Berlin B/5656[1]HistoryOpened1 July 1989; 34 years ago (1989-07-01)Services Precedi...

Time period between 1 January 1801 and 31 December 1900 For other uses, see 19th century (disambiguation). Millennium 2nd millennium Centuries 18th century 19th century 20th century Timelines 18th century 19th century 20th century State leaders 18th century 19th century 20th century Decades 1800s 1810s 1820s 1830s 1840s 1850s 1860s 1870s 1880s 1890s Categories: Births – Deaths Establishments – Disestablishments vte Napoleon Bonaparte, Empe...

German actor This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Peter Jordan actor – news · newspapers · books · scholar · JSTOR (February 2022) (Learn how and when to remove this template mes...

Aspect of history surrounding the Philippines' politics Emilio Aguinaldo, who led the Philippine Revolution against Spain, and Manuel L. Quezon, President of the autonomous Commonwealth of the Philippines under the United States Early polities in what is now the Philippines were small entities known as barangays, although some larger states were established following the arrival of Hinduism and Islam through regional trade networks. The arrival of Spanish settlers began a period of Spanish ex...

Japanese baseball player This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Kenshin Hotta – news · newspapers · books · scholar · JSTOR (April 2022) (Learn how and when to remove this template mess...

Village in Goa, IndiaLoliem-PolemVillageLoliem-PolemLocation in Goa, IndiaShow map of GoaLoliem-PolemLoliem-Polem (India)Show map of IndiaCoordinates: 14°54′N 74°05′E / 14.90°N 74.09°E / 14.90; 74.09Country IndiaStateGoaDistrictSouth GoaLanguages • OfficialKonkaniTime zoneUTC+5:30 (IST)PIN403728Telephone code91-08346-XXX XXXVehicle registrationGANearest cityKarwarWebsitegoa.gov.in Loliem-Polem is a village located in the southernmost tip of the...

Indian actress and producer Suchitra Bandekarwith Aadesh BandekarBornSuchitra Gudekar (1972-10-10) 10 October 1972 (age 51)Nashik, MaharashtraOccupationsActressProducerYears active1994-presentSpouse Aadesh Bandekar ​(m. 1990)​[1]ChildrenSoham Bandekar[2] Suchitra Bandekar is an Indian actress. She mainly works in Hindi and Marathi films and television.[3][4] Childhood She was born and brought up in Nashik, Maharashtra.[...

Jalan Tol Semarang–BatangInformasi ruteBagian dari Jalan Tol Trans-JawaDikelola oleh PT Jasamarga Semarang Batang (JSB)Panjang:75 km (47 mi)Berdiri:20 Desember 2018; 4 tahun lalu (2018-12-20) – sekarangPersimpangan besarUjung Barat: Jalan Tol Pemalang-Batang Simpang Susun KandemanSimpang Susun GringsingSimpang Susun WeleriSimpang Susun KendalSimpang Susun KaliwunguSimpang Susun KrapyakUjung Timur: Jalan Tol SemarangLetakKota besar:Kota SemarangKendalBatangSistem ja...

This article's use of external links may not follow Wikipedia's policies or guidelines. Please improve this article by removing excessive or inappropriate external links, and converting useful links where appropriate into footnote references. (December 2022) (Learn how and when to remove this template message) Work of Tamil Hindu literature Modern book cover of volume two of the text Nammalvar, considered the most prominent of the twelve Alvars whose works are compiled as Prabandam Part of a ...

Bulbophyllum fimbriatum Klasifikasi ilmiah Kerajaan: Plantae (tanpa takson): Angiospermae (tanpa takson): Monocots Ordo: Asparagales Famili: Orchidaceae Genus: Bulbophyllum Spesies: Bulbophyllum fimbriatum Nama binomial Bulbophyllum fimbriatum(Lindl.) Rchb.f. in W.G.Walpers 1861 Bulbophyllum fimbriatum adalah spesies tumbuhan yang tergolong ke dalam famili Orchidaceae. Spesies ini juga merupakan bagian dari ordo Asparagales. Spesies Bulbophyllum fimbriatum sendiri merupakan bagian dari genus ...

This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: 2007 İstanbul Cup – news · newspapers · books · scholar · JSTOR (March 2017) (Learn how and when to remove this template message) Tennis tournament2007 İstanbul CupDate21 – 26 MayEdition3rdCategoryWTA Tier IIISurfaceClay / OutdoorLocationIstanbul, TurkeyChampionsSingles Elena DementievaDoubles Agnieszk...

Kembali kehalaman sebelumnya