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 four 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:

Jozef-Ernest van RoeyKardinal, Uskup Agung MechelenPrimat BelgiaGerejaKatolik RomaKeuskupan agungMechelenMasa jabatan12 Maret 1926 - 6 Agustus 1961PendahuluDésiré-Joseph MercierPenerusLeo Joseph SuenensJabatan lainKardinal-Imam Santa Maria in Ara CoeliVikar Apostolik Militer BelgiaImamatTahbisan imam18 September 1897Tahbisan uskup25 April 1926oleh Clemente MicaraPelantikan kardinal20 Juni 1927oleh Pius XIPeringkatKardinal-ImamInformasi pribadiLahir(1874-01-13)13 Januari 1874Vorselaar, Bel…

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: コルク – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2017年4月) コルクを打ち抜いて作った瓶の栓 コルク(木栓、蘭&…

Halaman ini berisi artikel tentang the province in the Philippines. Untuk kegunaan lain, lihat Pangasinan (disambiguasi). PangasinanProvinsi BenderaLambangJulukan: Heartland of the Philippines; Land of Miracles and Romance; Premier Province of the NorthMap of the Philippines with Pangasinan highlightedNegaraFilipinaRegionIlocos (Region I)Didirikan1580IbukotaLingayenPemerintahan • JenisProvince of the Philippines • GubernurAmado Espino (NPC) • Wakil gubern…

South African rugby union player Rugby playerWerner KokDate of birth (1993-01-17) 17 January 1993 (age 31)Place of birthMbombela, South AfricaHeight1.80 m (5 ft 11 in)Weight96 kg (212 lb; 15 st 2 lb)SchoolHoërskool Nelspruit, NelspruitRugby union careerPosition(s) Centre / WingerCurrent team Sharks / Sharks (Currie Cup)Youth career2009–2011 Pumas2012 Western ProvinceSenior careerYears Team Apps (Points)2016–2018 Western Province 15 (30)2019 Stade Toul…

Vous lisez un « bon article » labellisé en 2012. Pour les articles homonymes, voir Karembeu. Christian Karembeu Christian Karembeu en 2014 Biographie Nom Christian Lali Kake Karembeu[k 1] Nationalité Française Naissance 3 décembre 1970 (53 ans) Lifou (Nouvelle-Calédonie) Taille 1,77 m (5′ 10″) Poste Milieu de terrain Pied fort Droit Parcours junior Années Club 1985-1988 Gaïtcha FCN 1988-1990 FC Nantes Parcours senior1 AnnéesClub 0M.0(B.) 1990-1995 FC Nantes…

هذه المقالة عن المجموعة العرقية الأتراك وليس عن من يحملون جنسية الجمهورية التركية أتراكTürkler (بالتركية) التعداد الكليالتعداد 70~83 مليون نسمةمناطق الوجود المميزةالبلد  القائمة ... تركياألمانياسورياالعراقبلغارياالولايات المتحدةفرنساالمملكة المتحدةهولنداالنمساأسترالياب…

土库曼斯坦总统土库曼斯坦国徽土库曼斯坦总统旗現任谢尔达尔·别尔德穆哈梅多夫自2022年3月19日官邸阿什哈巴德总统府(Oguzkhan Presidential Palace)機關所在地阿什哈巴德任命者直接选举任期7年,可连选连任首任萨帕尔穆拉特·尼亚佐夫设立1991年10月27日 土库曼斯坦土库曼斯坦政府与政治 国家政府 土库曼斯坦宪法 国旗 国徽 国歌 立法機關(英语:National Council of Turkmenistan) 土…

Частина серії проФілософіяLeft to right: Plato, Kant, Nietzsche, Buddha, Confucius, AverroesПлатонКантНіцшеБуддаКонфуційАверроес Філософи Епістемологи Естетики Етики Логіки Метафізики Соціально-політичні філософи Традиції Аналітична Арістотелівська Африканська Близькосхідна іранська Буддійсь…

I comuni di Panama (in spagnolo corregimientos) sono una suddivisione amministrativa di terzo livello del paese centro americano. I 66 distretti di Panama sono formati complessivamente da 693 comuni. Le città (in spagnolo ciudad) di Colón e La Chorrera sono formate da due comuni ciascuna, mentre la capitale Panama da 13. Al censimento del 2010 il comune più popoloso era Juan Díaz, uno dei comuni che formano la capitale, con 100.630 abitanti mentre il meno abitato era La Guinea nel distretto …

فاكوندو توريس   معلومات شخصية الميلاد 13 أبريل 2000 (العمر 24 سنة)مونتفيدو[1]  الطول 1.77 م (5 قدم 9 1⁄2 بوصة) مركز اللعب وسط الجنسية الأوروغواي  معلومات النادي النادي الحالي أورلاندو سيتي الرقم 17 مسيرة الشباب سنوات فريق 2010–2020 بنيارول المسيرة الاحترافية1 سنوا…

Patrick J. AdamsAdams di promosi acara Suits, 2013LahirPatrick Johannes Adams [1]27 Agustus 1981 (umur 42)Toronto, Ontario, KanadaKebangsaanKanadaPekerjaanAktor FotograferTahun aktif2001–sekarangPasanganTroian Bellisario(2010–sekarang; bertunangan) Patrick Johannes Adams (lahir 27 Agustus 1981) adalah seorang aktor Kanada. Ia dikenal akan perannya sebagai Mike Ross dalam serial televisi Suits.[2] Kehidupan awal dan pendidikan Adams mengenyam pendidikan di Northern S…

  جمهورية غانا Republic of Ghana  (إنجليزية) غاناعلم غانا غاناشعار غانا الشعار الوطنيالاتحاد والعدالة النشيد: الله يبارك وطننا غانا الأرض والسكان إحداثيات 8°02′N 1°05′W / 8.03°N 1.08°W / 8.03; -1.08   [1] أعلى قمة جبل أفادجا  أخفض نقطة خليج غينيا (0 متر)  المساحة 238,535 ك…

Austronesian language of the Philippines Not to be confused with Ongan languages. OnhanLoocnon, InonhanNative toPhilippinesRegionRomblonNative speakers86,000 (2000)[1]Language familyAustronesian Malayo-PolynesianPhilippineCentral PhilippineBisayanWestern BisayanOnhanLanguage codesISO 639-3locGlottologinon1237Inonhan language map based on Ethnologue Onhan is a regional Western Bisayan language spoken, along with the Romblomanon and Asi languages, in the province of Romblon, Phil…

Soviet space station in orbit from April to October 1971 Salyut 1 (DOS-1)Salyut 1 as seen from the departing Soyuz 11Station statisticsCOSPAR ID1971-032ASATCAT no.05160Call signSalyut 1Crew3LaunchApril 19, 1971, 01:40:00 (1971-04-19UTC01:40) UTC[1]Carrier rocketProton-KLaunch padSite 81/24, Baikonur Cosmodrome, Soviet UnionReentryOctober 11, 1971 (1971-10-12)Mission statusDe-orbitedMass18,425 kg (40,620 lb)Length~20 m (66 ft)Diameter~4 m (13 f…

This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Atomic Minerals Directorate for Exploration and Research – news · newspapers · books · scholar · JSTOR (November 2019) (Learn how and when to remove this message) Atomic Minerals Directorate for Exploration and Research (AMD)TypeExploration and ResearchEstablished1948DirectorB Sara…

Autonomous community of Spain For other uses of Extremadura, see Extremadura (disambiguation). You can help expand this article with text translated from the corresponding article in Spanish. (March 2018) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-trans…

31°03′59″N 35°41′56″E / 31.066282°N 35.698979°E / 31.066282; 35.698979 مقام وضريح الصحابي عَبدُ الله بن رَوَاحَة تقديم البلد  الأردن مدينة بلدة المزار في محافظة الكرك إحداثيات 31°03′59″N 35°41′56″E / 31.066282°N 35.698979°E / 31.066282; 35.698979   نوع مقام وضريح تصنيف ديني الموقع الجغرافي تع…

This article uses bare URLs, which are uninformative and vulnerable to link rot. Please consider converting them to full citations to ensure the article remains verifiable and maintains a consistent citation style. Several templates and tools are available to assist in formatting, such as reFill (documentation) and Citation bot (documentation). (August 2022) (Learn how and when to remove this message) The ES7000 is Unisys's x86/Windows, Linux and Solaris-based server product line.[1] The…

Questa voce o sezione sull'argomento musei della Svizzera non cita le fonti necessarie o quelle presenti sono insufficienti. Puoi migliorare questa voce aggiungendo citazioni da fonti attendibili secondo le linee guida sull'uso delle fonti. KunsthausLa Kunsthaus Zürich UbicazioneStato Svizzera LocalitàKreis 1 e Zurigo IndirizzoHeimplatz 1, 8001 Zürich Coordinate47°22′13″N 8°32′53″E47°22′13″N, 8°32′53″E CaratteristicheTipopittura Istituzione1819 DirettoreAnn Demee…

En Marea Portavoz parlamentario Luis VillaresFundación Noviembre de 2015 (como coalición)30 de julio de 2016 (como partido)Disolución 26 de septiembre de 2020Ideología ProgresismoEcologismoSocialismo democráticoDemocracia participativaFederalismoNacionalismo gallegoPosición IzquierdaPartidoscreadores Anova-Irmandade NacionalistaPodemos GaliciaEsquerda UnidaSede Rúa Eduardo Pondal, 31, 15701 Santiago de CompostelaPaís España EspañaSitio web enmarea.gal[editar datos en Wikidata…