【问题标题】:Modify PID manager for multi-threading为多线程修改 PID 管理器
【发布时间】:2016-02-06 23:16:03
【问题描述】:

下面是我的 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)));
}

【问题讨论】:

  • 您需要使您的 allocate_pidrelease_pid 函数线程安全。

标签: c linux multithreading pid


【解决方案1】:

Posix 线程是执行此操作的最简单和规范的方法。

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

基本上,您通过pthread_create() 创建线程实例,然后加入它们或通过pthread_join()“等待它们完成”。

请注意,Wikipedia 条目还提到了使用 gcc 进行编译的一些内容。 -pthread-lpthread 在那里是绝对必要的,否则你会得到未定义的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2013-05-26
    • 2011-08-29
    • 2010-10-08
    • 2013-06-04
    相关资源
    最近更新 更多