學習pthreads,管理執行緒的棧

2021-06-23 04:42:01 字數 1603 閱讀 5090

程序的位址空間分成**段,靜態資料段,堆和棧段。執行緒棧的位置和大小是從它所屬的程序的棧中切分出來的。每個棧必須足夠大,以容納所有對等執行緒的函式的執行以及它們將會呼叫的例程鏈。或許你會問為什麼要進行執行緒棧的管理?因為棧的管理由系統自動管理。但是針對具體問題,有可能系統自動管理的棧不能滿足執行的要求,這時對執行緒的棧的管理是必要的。本文分為三個部分,第一部分給出管理執行緒棧的**示例,第二部分對**進行講解,第三部分給出執行結果。

一 **示例

本例程利用執行緒的屬性物件,獲取棧的大小,並改變棧的大小。

#include "stdafx.h"

#include

#include

#include

#define nthreads 4

#define n 1000

#define megextra 1000000

pthread_attr_t attr;

void *dowork(void *threadid)

int main(int argc, char *argv)

定義全域性屬性物件變數attr,定義執行緒所需要執行的函式dowork,該函式通過pthread_attr_getstacksize ()獲取所執行執行緒的棧大小,列印輸出。

pthread_t threads[nthreads];

size_t stacksize;

int rc;

long t;

定義程式所需變數,其中stacksize

是以位元組為單位的變數,用於儲存棧的大小。

pthread_attr_init(&attr);

pthread_attr_getstacksize (&attr, &stacksize);

printf("default stack size = %li\n", stacksize);

使用預設值初始化屬性物件變數,利用pthread_attr_getstacksize ()獲取棧的大小,然後列印輸出。

stacksize = sizeof(double)*n*n+megextra;

printf("amount of stack needed per thread = %li\n",stacksize);

pthread_attr_setstacksize (&attr, stacksize);

printf("creating threads with stack size = %li bytes\n",stacksize);

將新的棧大小值賦給stacksize,使用pthread_attr_setstacksize (&attr, stacksize)函式設定屬性物件所將要執行執行緒的棧大小,並列印輸出。

for(t=0; t
按照屬性物件建立執行緒,然後終止執行緒。三 執行結果

Pthreads執行緒庫

posix執行緒是執行緒的posix標準,定義了建立和操縱執行緒的一套api。實現posix 執行緒標準的庫常被稱作pthreads,一般用於unix like posix 系統,如linux solaris。但是microsoft windows上的實現也存在,例如直接使用windows api實...

學習pthreads,多執行緒的建立和終止

一 示例 本程式建立了5個執行緒,分別輸出hello world 以及執行緒編號。include stdafx.h include include include define num threads 5 void printhello void threadid int main int argc...

pthreads多執行緒資料採集

以前使用curl的多執行緒並不是真正的多執行緒,只是一種模擬的多執行緒,現在使用pthreads來實現真正意義上的多執行緒。windows下 mac unix linux下 安裝方式 windows下 解壓得到pthreadvc2.dll和php pthreads.dll檔案,把vc2檔案放到php...