c++ multi threading priority implementation failed - c++

=)
i am a new user here, and I am new to c++, so it is a bit hard for me to work on it...
so i am asking you guys some questions! =)
i am doing a work for school, that asks me to implement threading priority into this:
#include <pthread.h>
#include <stdio.h>
#include <sched.h>
int sched_yield(void);
// Parameters to print_function.
struct char_print_parms{
char character; // char to print
int count; // times to print
};
void* char_print (void* parameters){
int i;
struct char_print_parms* p;
p = (struct char_print_parms*) parameters;
for (i = 0; i < p->count; ++i){
fputc (p->character, stderr);
sched_yield();
}
return NULL;
}
int main (){
pthread_t thread1_id,thread2_id;
struct char_print_parms thread1_args,thread2_args;
// Create a new thread to print 200 x's.
thread1_args.character = 'x';
thread1_args.count = 200;
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
// Create a new thread to print 200 o's.
thread2_args.character = 'o';
thread2_args.count = 200;
pthread_create (&thread2_id, NULL,
&char_print, &thread2_args);
// main waits for the threads to complete
pthread_join(thread1_id, NULL);
pthread_join(thread2_id, NULL);
return 0;
}
This gives is "oxoxoxo..." etc.
The objective is to get more "o", until it finishes.
What I did was:
#include <pthread.h>
#include <stdio.h>
#include <sched.h>
int sched_yield(void);
// Parameters to print_function.
struct char_print_parms{
char character; // char to print
int count; // times to print
};
void* char_print (void* parameters){
int i;
struct char_print_parms* p;
p = (struct char_print_parms*) parameters;
for (i = 0; i < p->count; ++i){
fputc (p->character, stderr);
sched_yield();
}
return NULL;
}
int main (){
pthread_t thread1_id,thread2_id;
struct char_print_parms thread1_args,thread2_args;
//new code lines
struct sched_param param;
pthread_attr_t pta;
pthread_attr_init(&pta);
pthread_attr_getschedparam(&pta, &param);
//end of new code lines
// Create a new thread to print 200 x's.
thread1_args.character = 'x';
thread1_args.count = 200;
//more new code lines
param.sched_priority = 0;
pthread_attr_setschedparam(&pta, &param);
pthread_setschedparam(thread1_id, SCHED_OTHER, &param);
//end of more new code lines
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
// Create a new thread to print 200 o's.
thread2_args.character = 'o';
thread2_args.count = 200;
//more new code lines 2
param.sched_priority = 10;
pthread_attr_setschedparam(&pta, &param);
pthread_setschedparam(thread2_id, SCHED_OTHER, &param);
//end of more new code lines 2
pthread_create (&thread2_id, NULL,
&char_print, &thread2_args);
// main waits for the threads to complete
pthread_join(thread1_id, NULL);
pthread_join(thread2_id, NULL);
return 0;
}
At the end, I compile and try to run, but it appears an error:
Segmentation failed (core dumped)
Once again, I am new to c++ and my english is not very good, but I want to try to understand why this does not work. Any help is welcome!

When you call pthread_setschedparam the thread id variables haven't been initialized yet. So you're trying to change parameters on an indeterminate thread.
The easiest way to change the priority is to do it in the thread themselves.
Regarding uninitialized local variables, their values are indeterminate until explicitly initialized. Using uninitialized local variables leads to undefined behavior.
If you see the example in the pthread_setschedparam you see it being called with pthread_self to set the own threads priority. You can use this to either add a field in the structure you pass to the thread that contains the priority, or have a wrapper thread-function which sets the priority and then calls the actual thread function.

You should first call pthread_create (&thread1_id, NULL, &char_print, &thread1_args); to create thread thread1_id, then you can set this thread's priority. I modify the code and it works fine.
thread1_args.character = 'x';
thread1_args.count = 200;
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
//more new code lines
param.sched_priority = 0;
pthread_attr_setschedparam(&pta, &param);
pthread_setschedparam(thread1_id, SCHED_OTHER, &param);
// Create a new thread to print 200 o's.
thread2_args.character = 'o';
thread2_args.count = 200;
pthread_create (&thread2_id, NULL, &char_print, &thread2_args);
//more new code lines 2
param.sched_priority = 10;
pthread_attr_setschedparam(&pta, &param);
pthread_setschedparam(thread2_id, SCHED_OTHER, &param);
You can read this link:https://access.redhat.com/site/documentation/en-US/Red_Hat_Enterprise_MRG/2/html/Realtime_Reference_Guide/chap-Realtime_Reference_Guide-Priorities_and_policies.html.
I test this code, but the output is different each time.

Related

Xlib : Segmentation fault on multithreading

My attempt is to write an Xlib wrapper for the purpose of implementing triple buffering methods. Using which a person needs only compute their display matrix and forward it to the API for displaying. I have two separate threads for handling events and display. The events thread seems to execute without any issue, however, the display thread, when used with standard Xlib functions such as XDrawRectangle, XFillArc, XSetForeground, etc. seems to cause a segmentation fault of an unknown nature.
This is my thread execution part :
int startx(){
pthread_t eventsThread, displayThread;
char msg1[15] ="Events Thread", msg2[15] = "Display Thread";
int pid1, pid2;
pid1 = pthread_create( &eventsThread, NULL, eventsHandler, (void*) msg1);
pid2 = pthread_create( &displayThread, NULL, displayHandler, (void*) msg2);
pthread_join(eventsThread, NULL);
pthread_join(displayThread, NULL);
return 0;
};
This is my displayHandler :
void *displayHandler(void* args){
cout<<connectionNumber<<endl;
Color c(50,50,250);
int width = 40, height = 60,x = 500, y = 100;
for(int i=0;i<1300;i++){
XSetForeground(display, xgraphics, c.decimal);
XDrawRectangle(display, mainWindow, xgraphics, x, y, width, height);
XFlush(display);
}
}
The eventsThread seems to be executing without error. Also, I have tried making the display function a part of the main program, with the same results.
If somebody could tell me an alternative/correct method to paint the window using matrices, it would be most appreciated.
Note : Color is a self made class for ease of colour computation.
This crashes for me before the howdy line. Uncommenting the return NULL; line makes it work.
#include <iostream>
#include <pthread.h>
void *displayHandler(void* args) {
char* txt = reinterpret_cast<char*>(args);
std::cout << txt << "\n";
// return NULL;
}
int startx(){
pthread_t displayThread;
char msg2[15] = "Display Thread";
int pid2;
pid2 = pthread_create( &displayThread, NULL, displayHandler, (void*) msg2);
pthread_join(displayThread, NULL);
return 0;
}
int main() {
startx();
std::cout << "howdy\n";
}
As Ted Lyngmo points out. The problem lay with the fact that Xlib has no thread safety implemented for writing to the display. So writing a mutex presented a solution.
If any of the event masks are set to write to the screen, separate threads for both become pointless. Instead making the masks toggle variables, allow them to work simultaneously.

Capture value from infinite thread c++

I have created a thread that is running parrallel with main thread. Both threads are doing something infinitely (both have while(true) statement). Main thread while(true) is creating game logic in frames, and second thread is receiveing messages from socket.
Is it possible to get string value of message received from second thread into main thread each frame without returning from second thread?
In c#, I would do it with method invoker but I didn't find anything helpful for c++. Is it possible to perform in c++?
Function which creates thread:
void ReceiveMessage() {
//std::promise<int> p;
//auto f = p.get_future();
char buf[1024];
string usernput;
int bytesReceived = 0;
std::thread receiveMessage(&FactoredThread::ThreadFunction, *this);
receiveMessage.detach();
//pokusajporuke = f.get();
}
ThreadFunction:
void ThreadFunction() {
bytesReceived = 0;
while (true) {
bytesReceived = recv(sock, buf, 1024, 0);
if (bytesReceived > 0) {
string primljeniString = "";
for (int i = 0; i < sizeof(buf); i++) {
if (buf[i] != 0)
{
primljeniString += buf[i];
}
}
ZeroMemory(buf, 1024);
pokusajporuke = primljeniString;
}
}
}
So how to get "pokusajporuke" string for main thread?
Yes, sure. There are many ways of solving this problem.
One way is to use signals and slots, like in Qt. For pure C++ you could use Boost.Signals2, which is thread safe.
Or you can realize pattern producer-consumer. One thread(producer) puts values into buffer(it should be thread-safe buffer), second takes them from there.
I think, for your problem second way is better.
Actually what I needed was global static variable. And then with another method from main thread I put that global variable into class property

Returning code from pthread creation in C++ is 11

I have thread creation problem using Pthread. My code is as follows. I show only some portion due to space constraints.
Main.c create Detectdirection instance and send to the function.
d = new Detectdirection();
while(run)
{
int ret = d->run_parallel(d);
if(ret == -1)
run = false;
}
My Detectdirection Class has two functions to run in parallel:
class Detectdirection{
public:
int run_parallel(void*p);
void *Tracking(void *p);
static void *Tracking_helper(void * p);
void *ReadImage(void *p );
static void *ReadImage_helper(void *p );
private:
pthread_t thread[2];
}
void *Detectdirection::ReadImage(void *p){
Detectdirection *app = (Detectdirection*)p;
while(run){
}
pthread_exit(NULL);
}
void *Detectdirection::Tracking(void *p){
Detectdirection *app = (Detectdirection*)p;
while(run){
}
pthread_exit(NULL);
}
void *Detectdirection::Tracking_helper(void *p){
Detectdirection *app = (Detectdirection*)p;
return ((Detectdirection*)p)->Tracking(app);
}
void *Detectdirection::ReadImage_helper(void *p ){
Detectdirection *app = (Detectdirection*)p;
return ((Detectdirection*)p)->ReadImage(app);
}
int Detectdirection::run_parallel(void* p){
Detectdirection *app = (Detectdirection*)p;
int rc = pthread_create(&thread[0], NULL, app->ReadImage_helper, app);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
return -1;
}
rc = pthread_create(&thread[1], NULL, app->Tracking_helper, app);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
return -1;
}
return 0;
}
Compile is ok and when I run, I have thread creation error. That sort of return type 11 happens only when many threads are created. But now I create only two thread and I have that error. What could be wrong?
I believe your are getting EAGAIN (based on the error code 11). That (obivously) means your system doesn't have enough resources to create threads anymore.
POSIX documentation says:
[EAGAIN] The system lacked the necessary resources to create another
thread, or the system-imposed limit on the total number of threads in
a process {PTHREAD_THREADS_MAX} would be exceeded.
I am not quite sure the following is true.
But now I create only two thread and I have that error. What could be wrong?
Here,
while(run)
{
int ret = d->run_parallel(d);
if(ret == -1)
run = false;
}
You are creating in a loop and each call d->run_parallel() creates two threads. So, you are potentially creating infinite number of threads
as the loop only breaks when pthread_create() fails. So, you may want to look at this loop carefully whether you really want to do as it is right now.
You don't seem to join with the threads you create. So, you could detach the threads so that thread-specific resources are released immediately when the thread(s) exit.
You can do:
pthread_detach(pthread_self());
in both ReadImage_helper() and Tracking_helper() functions to detach them. This could potentially solve your resource issue.
If it's still present then you have to look at ways to limit the number of threads that are simultaneously running on your system. One possible option is to use thread pools -- create a fixed number of threads and assign them new tasks as the threads complete their current task(s).

Understanding unix child processes that use semaphore and shared memory

I'm going to do my best to ask this question with the understanding that I have.
I'm doing a programming assignment (let's just get that out of the way now) that uses C or C++ on a Unix server to fork four children and use semaphore and shared memory to update a global variable. I'm not sure I have an issue yet, but my lack of understanding has me questioning my structure. Here it is:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define NUM_REPEATS 10
#define SEM_KEY 1111
#define SHM_KEY 2222
int globalCounter = 0;
/***** Test function for confriming a process type ******/
int checkProcessType(const char *whoami)
{
printf("I am a %s. My pid is:%d my ppid is %d\n",
whoami, getpid(), getppid() );
for(int i = 1; i<=3; i++){
printf("%s counting %d\n", whoami, i);
}
return 1;
}
void
int main (void) {
pid_t process_id; // PID (child or zero)
int sharedMemID; // Shared memory ID
int sharedMemSize; // shared memory size
struct my_mem * sharedMemPointer; // pointer to the attached shared memory
// Definition of shared memory //
struct my_mem {
long counter;
int parent;
int child;
};
// Gathering size of shared memory in bytes //
sharedMemSize = sizeof(my_mem);
if(sharedMemSize <= 0){
perror("error collection shared memory size: Exiting...\n");
exit(0);
}
// Creating Shared Memory //
sharedMemID = shmget(SHM_KEY, sharedMemSize, 0666 | IPC_CREAT);
if (sharedMemID < 0) {
perror("Creating shared memory has failed: Exiting...");
exit(0);
}
// Attaching Shared Memory //
sharedMemPointer = (struct my_mem *)shmat(sharedMemID, NULL, 0);
if (sharedMemPointer == (struct my_mem*) -1) {
perror("Attaching shared memory has failed. Exiting...\n");
exit(0);
}
// Initializing Shared Memory //
sharedMemPointer->counter = 0;
sharedMemPointer->parent = 0;
sharedMemPointer->child = 0;
pid_t adder, reader1, reader2, reader3;
adder = fork();
if(adder > 0)
{
// In parent
reader1 = fork();
if(reader1 > 0)
{
// In parent
reader2 = fork();
if(reader2 > 0)
{
//In parent
reader3 = fork();
if (reader3 > 0)
{
//In parent
}
else if (reader3 < 0)
{
// Error
perror("fork() error");
}
else
{
// In reader3
}
}
else if(reader2 < 0)
{
//Error
perror("fork() error");
}
else
{
// In reader2
}
}
else if(reader1 < 0)
{
// Error
perror("fork() error");
}
else
{
// In reader1
}
}
else if(adder < 0 )
{
// Error
perror("fork() error");
}
else
{
// In adder
//LOOP here for global var in critical section
}
}
Just some info of what I'm doing (I think), I'm creating a hunk of shared memory that will contain a variable, lets call it counter that will strictly be updated by adder and by the parent which becomes a subtractor after all child processes are active. I'm still trying to figure out the semaphore stuff that I will be using so adder and subtractor execute in critical section, but my main question is this.
How can I know where I am in this structure? My adder should have a loop that will do some job (update global var), and the parent/subtractor should have a loop for its job (also update global var). And all the readers can look at any time. Does the loop placement for parent/subtractor matter? I basically have 3 locations I know I'll be in parent. But since all children need to be created first does it have to be in the last conditional after my third fork where I know I'm in parent? When I use my test method I get scattered outputs, meaning child one can be after parent's output, then child three, etc. It's never in any order, and from what I understand of fork that's expected.
I really have like three questions going on, but I need to first wrap my head around the structure. So let me just try to say this again concisely without any junk cause I'm hung up on loop and critical section placement that isn't even written up yet.
More directly, when does parent know the existence of all children and with this structure can one child do a task and somehow come back to it (i.e. adder/first child adding to global variable once, exits, and some other child can do its thing etc).
I still feel like I'm not asking the right thing, and I believe this is due to still trying to grasp concepts. Hopefully my stammering will kind of show what I'm stuck on conceptually. If not I can clarify.

Passing data recursively with threads

I am trying to pass values recursively with threading.
In my example, I am creating a thread and i pass it some data, and this thread creates another thread recursively, which also passes it some data.
The output is the following:
Thread 1: value = 8
Thread 2: value = 12318230
Why am I not getting the value 4 for the second thread even though I assigned it the value 4?
From my understanding (please correct me if I am wrong), each thread has its own stack. When I pass the value 4 to Thread 2 (the thread created by the first thread), the variable is in memory until the thread ends. Since I have a call to pthread_join, I wait until the child thread ends until I resume. I am uncertain why the value of Thread 2 is some random number.
int count = 0
typedef struct
{
int value;
} ThreadInfo;
void* ChildWork(void* a) {
pthread_t threadid;
count++;
if(count > 2)
pthread_exit(0);
ThreadInfo* info = (ThreadInfo*)a;
printf("value = %d\n", info->value);
ThreadInfo* child = new ThreadInfo;
child->value = 4;
pthread_create(&threadid, NULL, ChildWork, (void*)&child);
pthread_join(threadid, NULL);
pthread_exit(0);
}
int main(int argc, const char *argv[])
{
pthread_t threadid;
ThreadInfo info;
info.value = 8;
pthread_create(&threadid, NULL, ChildWork, (void*)&info);
pthread_join(threadid, NULL);
return 0;
}
ThreadInfo* child = new ThreadInfo;
child->value = 4;
pthread_create(&threadid, NULL, ChildWork, (void*)&child);
&child is a ThreadInfo** but the child thread casts it to a ThreadInfo* and reads garbage. Change (void*)&child to just child.