/*
* POSIX Real Time Example
* using a single pthread as RT thread
*/
/*gcc -o rt_example rt_example.c -lpthread -lrt -Wall
sudo ./rt_example */
#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
/*struct sched_param param;
pthread_attr_t attr;
pthread_t thread;
struct sched_param param1;
pthread_attr_t attr1;
pthread_t thread1;*/
struct sched_param param[2];
pthread_attr_t attr[2];
pthread_t thread[2];
void *thread_func(void *data)
{
/* Do RT specific stuff here */
printf("thread1: hello preempt_rt\n\r");
while(1)
pthread_testcancel();
return NULL;
}
void *thread_func1(void *data)
{
/* Do RT specific stuff here */
printf("thread2: hello preempt_rt\n\r");
while(1)
pthread_testcancel();
return NULL;
}
int rt_thread(void)
{
int ret;
param[0].sched_priority = 80;
ret = pthread_attr_setschedparam(&attr[0], ¶m[0]);
if (ret) {
printf("pthread setschedparam failed\n");
goto out;
}
/* Create a pthread with specified attributes */
ret = pthread_create(&thread[0], &attr[0], thread_func, NULL);
if (ret) {
printf("create pthread failed\n");
goto out;
}
out:
return ret;
}
int rt_thread1(void)
{
int ret;
param[1].sched_priority = 80;
ret = pthread_attr_setschedparam(&attr[1], ¶m[1]);
if (ret) {
printf("pthread setschedparam failed\n");
goto out;
}
/* Create a pthread with specified attributes */
ret = pthread_create(&thread[1], &attr[1], thread_func1, NULL);
if (ret) {
printf("create pthread failed\n");
goto out;
}
out:
return ret;
}
int main(int argc, char* argv[])
{
int ret=0;
void* retval;
int i;
/* Lock memory */
if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
printf("mlockall failed: %m\n");
exit(-2);
}
for(i=0;i<2;i++) {
/* Initialize pthread attributes (default values) */
ret = pthread_attr_init(&attr[i]);
if (ret) {
printf("init pthread attributes failed\n");
goto out;
}
/* Set a specific stack size */
ret = pthread_attr_setstacksize(&attr[i], PTHREAD_STACK_MIN);
if (ret) {
printf("pthread setstacksize failed\n");
goto out;
}
/* Set scheduler policy and priority of pthread */
ret = pthread_attr_setschedpolicy(&attr[i], SCHED_FIFO);
if (ret) {
printf("pthread setschedpolicy failed\n");
goto out;
}
/* Use scheduling parameters of attr */
ret = pthread_attr_setinheritsched(&attr[i], PTHREAD_EXPLICIT_SCHED);
if (ret) {
printf("pthread setinheritsched failed\n");
goto out;
}
}
rt_thread();
rt_thread1();
pthread_cancel(thread[0]);
pthread_cancel(thread[1]);
/* Join the thread and wait until it is done */
ret = pthread_join(thread[0],&retval);
if (ret)
printf("join pthread failed: %m\n");
printf("thread retval is %d\n",(int*)retval);
ret = pthread_join(thread[1],&retval);
if (ret)
printf("join pthread failed: %m\n");
printf("thread retval is %d\n",(int*)retval);
out:
return ret;
}
linux运行多线程
猜你喜欢
转载自blog.csdn.net/liuzq/article/details/83716112
今日推荐
周排行