修改PID管理器以进行多线程处理

时间:2016-02-06 23:16:03

标签: c linux multithreading pid

以下是我的PID经理。我想修改它,因此它使用多线程。因此我希望每个线程都能请求一个pid(也许就像我在while循环中那样创建20个左右),随机休息一段时间(我假设使用sleep()),然后释放pid(类似于你在下面看到的)。

对于C和Linux中的线程,我是一个全新手,所以如果有人可以帮我修改它。我会从clone()函数调用开始吗?

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define MIN_PID 300
#define MAX_PID 5000
#define CB CHAR_BIT

int sz = MAX_PID - MIN_PID + 1;

unsigned char *unsignedChar;

int allocate_map();
int allocate_pid();
void release_pid(int pid);

int main() 
{
    int map = allocate_map();
    if (map == 1) {
        printf("\nBitmap Data Structure initialized.\n");
        int id = 0, i = 0;

    //create 20 processes
        while (i < 20) {
            int val = allocate_pid();
            printf("\nProcess %d: pid = %d", i+1, val);
            i++;
        }
    //release a few processes
    release_pid(303); printf("\nProcess 303 released.");
    release_pid(308); printf("\nProcess 308 released.");
    release_pid(309); printf("\nProcess 309 released.");

    //allocate a few more processes after this release
        int val = allocate_pid(); printf("\nProcess %d : pid = %d", ++i, val); //should be 303
    val = allocate_pid(); printf("\nProcess %d : pid = %d\n", ++i, val); //should be 308
    }
    else printf("\nFailed to initialize data structure.\n");
}

/* Creates and initializes a bitmap data structure for representing pids;
 returns —1 for unsuccessful, 1 for successful */
int allocate_map() {
    unsignedChar = (unsigned char*)malloc((sz+CB-1)/CB * sizeof(char));
    if (unsignedChar) return 1;
    return -1;
}

/* Allocates and returns a pid; returns -1
if it is unable to allocate a pid (all pids are in use) */
int allocate_pid() {
    int i = 0;
    int pid = unsignedChar[i/CB] & (1 << (i & (CB-1)));
    while (pid != 0) {
        i++;
        pid = unsignedChar[i/CB] & (1 << (i & (CB-1)));
        }

    if (i+MIN_PID > MAX_PID) return -1;
    unsignedChar[i/CB] |= 1 << (i & (CB-1));
    return i+MIN_PID;
}

/* Releases a pid given a pid parameter*/
void release_pid(int pid) {
    if (pid < 300) {
        printf("\nInvalid PID: It should lie between 300 and 3000.");
        return;
    }
    int i = pid - MIN_PID;
    unsignedChar[i/CB] &= ~(1 << (i & (CB-1)));
}

1 个答案:

答案 0 :(得分:2)

Posix Threads是最简单和规范的方法。

Wikipedia已经有了一个很好的例子。

基本上,您可以通过pthread_create()创建线程实例并在此后加入它们,或者等待它们完成&#34;通过pthread_join()

请注意,Wikipedia条目还说明了使用gcc编译的内容。那里-pthread-lpthread是绝对必要的,否则您将获得未定义的引用。