开发者

Fault address when malloc/free pthread_t across threads

开发者 https://www.devze.com 2022-12-28 16:03 出处:网络
Fault address occurred when i malloc pthread_t to save a newly created thread id and free it in another thread. Codes as follows:

Fault address occurred when i malloc pthread_t to save a newly created thread id and free it in another thread. Codes as follows:

typedef struct _TaskInfo { 
    // int dummy_int;
    pthread_t tid;
} TaskInfo;

void* dummy_task(void* pArg) {
    free(pArg);
    return NULL;
}

void create_task() {
    TaskInfo *pInfo;
    pthread_attr_t attr;

    // set detached state stuff ...

    pInfo = (Task开发者_如何转开发Info*) malloc(sizeof(TaskInfo));
    pthread_create(&pInfo->tid, &attr, dummy_task, pInfo);

    // destroy pthread attribute stuff ...
}

int main() {
    int i;
    while(i < 10000) {
        create_task();
        ++i;
    }
    return 0;
}

When I uncomment the member dummy_int of TaskInfo it sometimes ran successfully, but sometimes failed. My platform is VMWare + Ubuntu 9.10 + ndk r3

Thanks!


pthread_create() stores the thread ID (TID) of the created thread in the location pointed to by the first parameter, however it does that after the thread is created (http://opengroup.org/onlinepubs/007908799/xsh/pthread_create.html):

Upon successful completion, pthread_create() stores the ID of the created thread in the location referenced by thread

Since the thread has already been created, it may well get a chance to run and delete that block of memory before pthread_create() gets a chance to store the TID in it.

When you don't have the dummy_int member in the struct you're probably corrupting the heap in a way that crashes early. With the dummy_int member included, you happen to be trashing something less sensitive (so the crashes are a bit less frequent). In either case, you're trashing memory that isn't allocated (or might not be allocated - you have a race condition).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号