linux多執行緒 9 匿名記憶體對映

2021-06-14 06:35:56 字數 1836 閱讀 4571

(1)使用/dev/zero檔案。

(2)形式上沒有檔案。

先看第一種,由於/dev/zero本來已經存在,因此open的時候不需要第三個引數,第二個引數指定為o_rdwr即可。

#include #include #include #include #include #include #include struct file_content

file_content;

#define nint 16

#define file_ "/dev/zero" // 對映檔案

intmain (int argc, char *argv)

//記憶體對映

pfc =

mmap (null, sizeof (file_content) + sizeof (int) * nint,

prot_read | prot_write, map_shared, fd, 0);

// 關閉檔案

close (fd);

if (pfc == map_failed)

sem_init (&(pfc->st), 1, 1); //訊號量初始化為1,用於互斥

setbuf(stdout,null); // 不加上這句的話,可能輸出會卡在那裡!

if (fork () == 0) //子程序

/*for (i = 0; i < nint; i++)

printf ("\n"); */

sem_post (&(pfc->st));

usleep(2000); }}

else // 父程序

/*for (i = 0; i < nint; i++)

printf ("\n");

*/sem_post (&(pfc->st));

usleep(2000);}}

if (munmap (pfc, sizeof (file_content) + sizeof (int) * nint) == -1)

return 0;

}

第二種,就是fd的位置用-1,然後呢,根本不開啟任何檔案。選項由map_shared變為map_shared|map_anon。

#include #include #include #include #include #include #include struct file_content

file_content;

#define nint 16

#define file_ "/dev/zero" // 對映檔案

intmain (int argc, char *argv)

sem_init (&(pfc->st), 1, 1); //訊號量初始化為1,用於互斥

setbuf(stdout,null); // 不加上這句的話,可能輸出會卡在那裡!

if (fork () == 0) //子程序

/*for (i = 0; i < nint; i++)

printf ("\n"); */

sem_post (&(pfc->st));

usleep(2000); }}

else // 父程序

/*for (i = 0; i < nint; i++)

printf ("\n");

*/sem_post (&(pfc->st));

usleep(2000);}}

if (munmap (pfc, sizeof (file_content) + sizeof (int) * nint) == -1)

return 0;

}

9 Linux多執行緒

linux系統下的多執行緒遵循posix執行緒介面,稱為pthread。編寫linux下的多執行緒程式,需要使用標頭檔案pthread.h,連線時需要使用庫libpthread.a。gcc lpthread helloworld.c o helloworld include int pthread ...

linux對映 Linux 匿名頁的反向對映

我們知道linux的記憶體管理系統中有 反向對映 這一說,目的是為了快速去查詢出乙個特定的物理頁在哪些程序中被對映到了什麼位址,這樣如果我們想把這一頁換出 swap 或是遷移 migrate 的時候,就能相應該更改所有相關程序的頁表來達到這個目的。物理記憶體的分頁機制,乙個pte page tabl...

多執行緒9 執行緒池

從原始碼中可以看出,執行緒池的建構函式有7個引數,分別是corepoolsize maximumpoolsize keepalivetime unit workqueue threadfactory handler 一 corepoolsize 執行緒池核心執行緒大小 執行緒池中會維護乙個最小的執行...