Xlib : Segmentation fault on multithreading - c++

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.

Related

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).

How to cause my C++ program to wait for sensor events for ever and not terminate

I'm trying to write a simple C++ app that registers to Windows sensor events.
I followed the MSDN documentaion and managed succesfully to get notifications when sensor events occur, my problem is that my main function ends, and so does the application.
How to i cuase it to wait forever for events to occur? Currently it registers and dies...
I have the following code:
My main looks like this:
int _tmain(int argc, _TCHAR* argv[])
{
RegisterToSensorEvents();
return 0;
}
void RegisterToSensorEvents()
{
ISensorManager* pSensorManager = NULL;
CoInitialize(NULL);
HRESULT hr = ::CoCreateInstance(CLSID_SensorManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pSensorManager));
// Get a collection of all sensors on the computer.
ISensorCollection* pSensorCollection = NULL;
hr = pSensorManager->GetSensorsByCategory(SENSOR_CATEGORY_ALL, &pSensorCollection);
EventsManager *pEventClass = NULL;
ISensorEvents* pMyEvents = NULL;
pEventClass = new(std::nothrow) EventsManager();
hr = pEventClass->QueryInterface(IID_PPV_ARGS(&pMyEvents));
ULONG numOfSensors;
pSensorCollection->GetCount(&numOfSensors);
for(int i=0; i< numOfSensors; i++)
{
ISensor *sensor = NULL;
pSensorCollection->GetAt(i,&sensor);
hr = sensor->SetEventSink(pMyEvents);
}
}
EventsManager is a class that derives from ISensorEvents and implements its callbacks, for example:
STDMETHODIMP EventsManager::OnDataUpdated(ISensor *pSensor,ISensorDataReport *pNewData)
{
cout <<"got here: Data Update" << endl;
}
I tried:
int _tmain(int argc, _TCHAR* argv[])
{
RegisterToSensorEvents();
while(true){}
return 0;
}
but seems like this infinte loop did not leave time for the program to process the incomming events, I tried adding Sleep in the loop body, but it didn't work either.
anyone?
UPDATE:
after investigation i see that the issue is different - seems like somehow my registartion of SetEventSink gets canceled and that is why i don't get any event notification.
if i copy this line:
hr = sensor->SetEventSink(pMyEvents); into my loop:
while(true)
{
hr = sensor->SetEventSink(pMyEvents);
}
the events are fired as expected. But it sounds to me very wrong to do such a thing.
Need to understand why this is hapenning.
Can anyone help?
Why don't you launch a new thread to do the listening, and just have the main function wait for an input?
How to simulate "Press any key to continue?"
Simple example of threading in C++
You can combine these to get your desired result.

SDL2 Threading Seg Fault

I am working on a rendering library for SDL2 and I am running into a seg fault when I try to do anything with the renderer. Through debugging I have determined that it is created correctly from the window (now...) However I cannot figure out why SDL2 is seg faulting when I call SDL_RenderClear(data->renderer)
The main thread calls:
int RenderThread::start(std::string title, int x, int y, int w, int h, Uint32 flags) {
data.window = SDL_CreateWindow(title.c_str(), x, y, w, h, flags);
if(data.window == NULL) return -2;
data.renderer = SDL_CreateRenderer(data.window, -1, 0);
if(data.renderer == NULL) return -3;
data.rlist->setRenderer(data.renderer);
data.run = true;
if(thread == NULL)
thread = SDL_CreateThread(renderThread, "RenderThread", (void*)(&data));
else return 1;
return 0;
}
Then the actual thread is:
int RenderThread::renderThread(void* d) {
RenderData* data = (RenderData*)d;
data->rlist->render(true);
SDL_SetRenderDrawColor(data->renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(data->renderer);
while(data->run) {
data->rlist->render();
SDL_RenderPresent(data->renderer);
SDL_Delay(data->interval);
}
return 0;
}
If you need to see more of the code it is all on github.
Some platforms (e.g. Windows) don't allow interacting with windows from threads other than the one that created them.
The documentation explicitly says this:
NOTE: You should not expect to be able to create a window, render, or receive events on any thread other than the main one.
From a design's perspective, trying to render from another thread becomes the source of many problems. For instance:
Is it desirable to (unpredictably) update an object more than once per frame? What's preventing a logic thread from trying to make many updates that can't be rendered?
Is it desirable to risk re-rendering without having the chance to update an object?
Will you lock the entire scene while the update happens? Or will each object get its own lock, so you don't try to render an object that's in the middle of an update? Is it desirable for the frame rate to be unpredictable, due to other threads locking the objects?
Not to mention the costs of synchronization primitives.

c++ multi threading priority implementation failed

=)
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.

Output for simple program using pthread

void cleanupHandler(void *arg) {
printf("In the cleanup handler\n");
}
void *Thread(void *string) {
int i;
int o_state;
int o_type;
pthread_cleanup_push(cleanupHandler, NULL);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &o_state);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &o_type);
puts("1 Hello World");
pthread_setcancelstate(o_state, &o_state);
puts("2 Hello World");
pthread_cleanup_pop(0);
pthread_exit(NULL);
}
int main() {
pthread_t th;
int rc;
rc = pthread_create(&th, NULL, Thread, NULL);
pthread_cancel(th);
pthread_exit(NULL);
}
I was wondering what the output of this code would be and in what order they would happen. Yes, this is a practice test question for an exam I have in 6 hours. Any help would be greatly appreciated. There are no office hours today as all of the TA's for my college are busy with their own finals.
Thanks
Here are the man pages you need to understand the problem they will be putting on the exam (which most certainly won't be the exact problem above.) So you need to understand what each of those functions does.
http://man7.org/linux/man-pages/man3/pthread_cleanup_push.3.html
http://man7.org/linux/man-pages/man3/pthread_setcanceltype.3.html,
http://man7.org/linux/man-pages/man3/pthread_cancel.3.html
http://man7.org/linux/man-pages/man3/pthread_exit.3.html
cleanup_push pushs a handler on a stack of functions that will be called if the calling thread is cancelled or exits.
setcancelstate temporarily locks out cancels (so that you can call setcanceltype atomically without weirdness happening.)
setcanceltype allows/disallows asynchronous cancellation notification.
cancel actually attempts to cancel the other thread.
exit exits from the calling thread.
You also need to understand whether pthread_setcancelstate is a cancellation point. You will find that information either on the above man pages or on http://man7.org/linux/man-pages/man7/pthreads.7.html.
In this question (and presumably the similar one that will be on your exam), you need to enumerate all possible interleavings of calls to these functions between the two threads.
1 Hello World
2 Hello World
Why not just compile it and run it? This version compiles and runs.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void cleanupHandler(void *arg) {
printf("In the cleanup handler\n");
}
void* Thread(void *string) {
int i;
int o_state;
int o_type;
sleep(1);
pthread_cleanup_push(cleanupHandler, NULL);
sleep(1);//Note that when you uncomment lines, you should uncomment them in order.
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &o_state);
sleep(1);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &o_type);
puts("1 Hello World");
sleep(1);
pthread_setcancelstate(o_state, &o_state);
sleep(1);
puts("2 Hello World");
pthread_cleanup_pop(0);
pthread_exit(NULL);
}
int main() {
pthread_t th;
int rc;
rc = pthread_create(&th, NULL, Thread, NULL);
pthread_cancel(th);
pthread_exit(NULL);
}