发新话题
打印

求救!内核多线程

求救!内核多线程

请教个位大侠如何实现内核多线程,包括线程的创建,销毁,挂起      

TOP

static void * thread_function(void *arg);

static char message[] = "Hello World";

int main()
{
        int res;
        pthread_t a_thread;
        void *thread_result;

        res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
        if (res != 0)
        {
                perror("Thread creation failed");
                exit(EXIT_FAILURE);
        }
        printf("Waiting for thread to finish...\n");
        res = pthread_join(a_thread, &thread_result);
        if (res != 0)
        {
                perror("Thread join failed");
                exit(EXIT_FAILURE);
        }

        printf("Thread joined, it returned %s\n", (char *)thread_result);
        printf("Message is now %s\n", message);
        exit(EXIT_SUCCESS);
}

static void *thread_function(void *arg)
{
        int i = 0;
        printf("thread_function is running. Argument was %s\n", (char *)arg);
        sleep(5);
        pthread_exit("Thank you for the CPU time");
        return 0;
}

线程的例子,推荐查看 Beginning_Linux_Programming_2nd_Edition.pdf 书
----------------------------------------------------------------------------------------
http://blog.csdn.net/fengyv      

TOP

非常感谢!但这好象是应用层的多线城,我需要实现内核底下的,例如用kernel_thread创建线城等,能否给我提供一些资料      

TOP

内核开发者们非常反对创建新的内核线程 (在有些场合,使用这种冒失的方法可能会吃到苦头),你可以使用内核提供的工作队列机制,内核缺省已经创建了工作者线程events/n(n为CPU号,一个CPU一个工作者线程)。你只需要把你要做的工作用DECLARE_WORK()或者INIT_WORK()描绘出来,包括工作名,工作函数和函数参数。再将其传递给schedule_work()就可以被工作者线程使用了。
如果你想创建属于自己的工作者线程,可以用create_workqueue()来创建。此时提交任务就不用schedule_work()而是queue_work()了。
      
依然记得从你口中说出再见坚决如铁,昏暗中有种烈日灼身的错觉; 依然记得从你眼中滑落的泪伤心欲绝,混乱中有种热泪烧伤的错觉....

TOP

发新话题