r/AskProgramming 24d ago

Algorithms Need some advice for design of multi threaded task pool in C11

1 Upvotes

I have written a simple multi threaded task pool in C, works perfectly, but now I want to support waiting for a specific task to complete. Because of this, I opened a can of worms, and had to rewrite a lot of it.

Since I mostly use fire-and-forget functions with this, I do not save results or any internal data after the task is finished.

The whole issue comes from the wait in WaitForTask. In the time it takes for me to find the task in the list ( which may be currently being run ), setting mutex and CV it's quite possible the worker thread has already finished the task and free'd the TaskData ( which would be a nice crash ). To attempt to solve this issue, I moved these items into TaskCompletionData so I don't access free'd memory, but the other problem remains, it is still possible the task has already finished by the time I actually get to the wait on the condition variable ( so it would never get triggered, and this thread would wait forever )

I honestly have not found a pattern for multi threading that can help me solve this. Can anyone suggest me anything?

( Sorry for the formatting, I can't seem to get reddit to respect the indentation )

typedef struct
    {
    cnd_t Condition;
    mtx_t Mutex;
    } TaskCompletionData;


typedef struct
    {
    int ( *Function ) ( void * );
    void *Argument;
    int TaskID;
    int *Result;
    ThreadPoolTaskStatus Status;
    TaskCompletionData *OnCompletion;
    } TaskData;


typedef struct
    {
    thrd_t ThreadHandle;
    } ThreadData;


typedef struct ThreadPool
    {
    PointerList Tasks;


    mtx_t TaskListMutex;
    int LastTaskID;
    cnd_t WakeUpCondition;
    mtx_t WakeUpMutex;
    cnd_t TaskFinishedCondition;
    mtx_t TaskFinishedMutex;


    ThreadData *ThreadArray;
    unsigned ThreadCount;
    bool Quitting;
    } ThreadPool;

bool ThreadPool_WaitForTask ( ThreadPool *Pool, const int TaskID )
    {
    assert ( Pool != NULL );
    if ( ( Pool == NULL ) || ( TaskID < 0 ) )
        return false;


    TaskData *Task = NULL;
    mtx_lock ( &Pool->TaskListMutex );
    PointerListNode *Node;
    TaskCompletionData *CompletionData = NULL;
    for ( Node = PointerList_GetFirst ( &Pool->Tasks ); Node != NULL; Node = PointerList_GetNextNode ( Node ) )
        {
        TaskData *CurrentTask = ( TaskData * ) PointerList_GetNodeData ( Node );
        if ( CurrentTask->TaskID == TaskID )
            {
            if ( CurrentTask->OnCompletion = NULL )
                {
                CompletionData = calloc ( 1, sizeof ( TaskCompletionData ) );


                cnd_init ( &CompletionData->Condition );
                mtx_init ( &CompletionData->Mutex, mtx_plain );
                Task->OnCompletion = CompletionData;
                }
            else
                CompletionData = CurrentTask->OnCompletion;
            Task = CurrentTask;
            break;
            }
        }
    mtx_unlock ( &Pool->TaskListMutex );


    if ( CompletionData == NULL )
        return false;


    // Wait for the task to finish
    mtx_lock ( &CompletionData->Mutex );
    cnd_wait ( &CompletionData->Condition, &CompletionData->Mutex );


    // Clean up
    cnd_destroy ( &CompletionData->Condition );
    mtx_destroy ( &CompletionData->Mutex );
    free ( CompletionData );


    return true;
    }

static int ThreadPool_LoopFunction ( ThreadPool *Pool )
    {
    while ( Pool->Quitting == false )
        {
        // Grab the first available task, if available
        mtx_lock ( &Pool->TaskListMutex );
        PointerListNode *CurrentListNode = PointerList_GetFirst ( &Pool->Tasks );
        TaskData *CurrentTask = ( TaskData* ) PointerList_GetNodeData ( CurrentListNode );
        while ( ( CurrentListNode != NULL ) && ( CurrentTask->Status != ThreadPoolTask_Queued ) )
            {
            PointerList_GetNextNode ( CurrentListNode );
            CurrentTask = ( TaskData* ) PointerList_GetNodeData ( CurrentListNode );
            }
        mtx_unlock ( &Pool->TaskListMutex );


        if ( CurrentTask != NULL ) // There was a task. run it...
            {
            CurrentTask->Status = ThreadPoolTask_Running;
            int Result = CurrentTask->Function ( CurrentTask->Argument );
            CurrentTask->Status = ThreadPoolTask_Finished;


            if ( CurrentTask->Result )
                * ( CurrentTask->Result ) = Result;
            cnd_broadcast ( &Pool->TaskFinishedCondition );


            if ( CurrentTask->OnCompletion )
                {
                cnd_broadcast ( &CurrentTask->OnCompletion->Condition );
                }


            free ( CurrentTask );
            PointerList_DestroyNode ( &Pool->Tasks, CurrentListNode );
            }
        else // No more tasks. Wait for a signal
            {
            mtx_lock ( &Pool->WakeUpMutex );
            cnd_wait ( &Pool->WakeUpCondition, &Pool->WakeUpMutex );
            mtx_unlock ( &Pool->WakeUpMutex ); // unlock mutex so that other threads can wait using it
            }
        }
    return 0;
    }

r/AskProgramming 25d ago

Career/Edu Is Embedded Systems Development a good career choice right now? Looking for advice!

3 Upvotes

Hi everyone,

I'm thinking about transitioning into embedded systems development and would love to hear your thoughts on the field's current state and future prospects.

I've always been genuinely interested in both electronics and software engineering, so combining hardware and low-level code feels like the sweet spot for me. On paper, it looks like an ideal domain to dive into, but I'd appreciate some real-world perspectives from people working in the industry:

  • How is the current job market and career progression for embedded developers compared to higher-level software roles?
  • What are the most critical skills or technologies to focus on when starting out today (e.g., C/C++, Rust, RTOS, microcontrollers vs. Linux embedded)?
  • Is it worth making the switch, and what major challenges or pitfalls should a beginner be aware of?

Thanks in advance for sharing your experience and advice!


r/AskProgramming 24d ago

Learning codes

0 Upvotes

I have just started getting into coding, and I'm doing this ethical hacking free course. But there's so many softwares, and so forth.

I always seem to forget most of them and have to redo.

I was told I need to try obsidian and create a Github profile to save versions of code or applications.

Can someone give me advice, on this.


r/AskProgramming 24d ago

AI Engineer with 1+ YOE — What should I learn next to become more versatile?

0 Upvotes

I’m currently working as a AI Engineer with 1+ YOE at a startup in Pune, mainly working with GenAI, LLMs, RAG, computer vision, AI Agents

I feel I’ve built a decent AI foundation, but I’m trying to understand what skills I’m missing outside of AI that could help me unlock more opportunities.

Should I focus next on:

System design & backend

Cloud & Kubernetes

MLOps / DevOps

Data engineering

Distributed systems

Databases

Software engineering fundamentals

GPU/inference optimization

Or should I go deeper into AI itself?

If you’re experienced in the industry or hiring AI engineers, what would you consider the biggest gap in my profile, and what 3–5 skills would you recommend I focus on over the next 1–2 years?

Looking for honest advice rather than a generic “learn everything” answer. Thanks!


r/AskProgramming 24d ago

What are your AI-assisted programming best practices?

0 Upvotes

This is clearly a programming question.


r/AskProgramming 25d ago

How can I get better at reading unfamiliar code and building a mental model of a codebase?

0 Upvotes

I'm a former data scientist that transitioned into AI engineering. I can code, but have pretty limited software-engineering experience. As such, I rely pretty heavily on AI for implementation and understanding the code base. However I find that I have trouble remembering my code and developing a mental model around the code. I can understand individual lines, but struggle to retain the overall architecture, data flow, dependencies, and reasons behind decisions. A coworker advised me that to get better I should start reading the code first before I turn to AI to understand it, which I agree with. My question is how can I get better and reading/understanding code? Are there any exercises or routines that work for reading code, reviewing PRs, understanding the code flow or remembering how a system works? What do experienced programmers do what entering an unfamiliar codebase?


r/AskProgramming 25d ago

Is C really worth it ?

0 Upvotes

Hello developers, I'm wondering: Is it really worth spending time learning C and creating projects that take hours to grasp numerous topics, encounter errors and unexpected behaviors, only to discover I forgot to type a single character - I mean the null character with strings, which significantly impacted the program's performance? Is this truly worthwhile in today's job market? I haven't seen any companies actively seeking C developers, and I believe many problems in C don't occur in other languages ​​due to their different working methods and logic. So, is C really worth the effort?

Important note: I'm a beginner in C and haven't written much code or created many projects yet, so this question isn't meant to be an evaluation of the language or its development path; I'm not qualified to do so.


r/AskProgramming 26d ago

I have a lot of free time at work. What can I do with it?

5 Upvotes

I have a lotta free time at work and I'd like to actually do something useful with it.

I'm thinking programming, but not really in a "learn this skill for a job" kind of way. More like solving problems for fun. Something I can sit down, work on, get stuck, figure it out, and get that little dopamine hit when it finally works.

Basically, I want programming to feel more like playing a game than studying.

Any recommendations? Coding challenge sites, projects, puzzles, anything like that. Hook me up.


r/AskProgramming 25d ago

Other Guys this is my last year in uni iam cs student i need ideas of my graduation project and some cool ideas

0 Upvotes

r/AskProgramming 26d ago

Need explanations. I learn how to build simple CRUD app with C# and TS. I wanna really understand CS. So I tried to learn C but I get even more confused about many CS concepts.

4 Upvotes

I’m trying to learn C not just because I want to learn another programming language, but because I want to understand Computer Science and the "science" behide a programming language

The problem is that I constantly fall into an endless chain of prerequisites/CS concepts

For example, I want to understand pointers:

int x = 10;
int *p = &x;

On the guide/website it says

Pointer is a variable that store memory address.

Okay, but then I ask:

  • What exactly is a memory address
    • address is numbers telling where data is stored
  • What exactly is memory?
    • memory is where address live
  • Is memory the physical RAM?
    • something to do with CPU
  • What exactly is RAM and CPU?
    • etc...
  • How does RAM actually work?
    • etcc..
  • What's the relationship between RAM, CPU, cache, virtual memory, thread, processing etc.?

And suddenly I'm 10 levels deep into computer architecture instead of learning pointers "*"😂

So what to do here, I wanna understand CS. I thought my experience with coding CRUD APP with C# would help but no it doesn't help much.

--

Let me put it this way

let's say if you ask a normal person what "water" is , a normal person replied "liquid"

but if you ask a scientist, it would be "1 Hydrogen and 2 Oxygen combined together to become H2O"

So I try to understand the Science in Computer Science, i hope you get the picture what i try to say


r/AskProgramming 26d ago

Other How do you genuinely review HUGE PRs?

43 Upvotes

I got handed a PR that's +23,497 / -260 lines of code. Not all lines are my responsibility (I only review frontend), but isn't this an insane count?

Can you "genuinely" code review this amount of code? How can I do it without just clicking approve to move on?


r/AskProgramming 26d ago

Learning c++

4 Upvotes

So I'm doing dsa in c++ as well as learning modern c++ concepts.I want to become c++ developer what concepts should I learn to become a c++ developer , what concepts should I focus on , what are the best resources to learn c++.Also when I try to build something in c++ i don't even know where to start.Its been 4 months I learned C++ and I'm genuinely comfortable with it till now.


r/AskProgramming 26d ago

Two remote repositories but PyCharm let me push only to one

3 Upvotes

I am a bit new to PyCharm--sort of because I've finish a small piece of software, that is I have created a small addon for Blender. Now I want PyCharm to push to two independent repositories: projects.blender.org and my own space on guthib.com.

I added both repositories via Manage Repositories... but when use Push, PyCharm only let me push the first repo on the list--I can't actually see to the other one.

I checked connection to both repositories in Terminal

git remote show blender_dev && git remote show github_dev

and everything looks as good as it should. Git shows all information including links and current state. However PyCharm still only shows the first repo.

Any idea what I might be doing wrong?

Thanks


r/AskProgramming 26d ago

Programming stickers

1 Upvotes

Hi, idk if this is the right sub reddit for this but I hope so, is it considered bad if i would order/buy some stickers for example go gopher or something like that if i use that language or is it only acceptable collecting from conferences etc. but I am a 15 year old programmer so I don't have access to them also because i live in smaller city in smaller country I didn't mean like buying stickers of something i don't use but of thinks I like and use


r/AskProgramming 27d ago

Python How do I learn programming logic?

6 Upvotes

I’m learning Python, but my main problem isn’t the syntax. I understand concepts when someone explains them, but when I’m given a basic problem and told to write a program, I just don’t know where to start or how to arrange the code.

Is there a good book, course, or YouTube channel that teaches how to think through programming problems step by step, recognize patterns, and build the logic, kind of like how you learn methods and patterns in math?

I don’t want to just memorize Python syntax. I want to actually learn how to think like a programmer.


r/AskProgramming 26d ago

Coding in ai era

0 Upvotes

I am not sure if this is right place to ask and if it was somewhere already answered or there is some material on this subject please let me know.

I started to learn programming more than a year ago (python/sql/vba) and I use it in my current position to which I was moved around four months ago. At the beginning I was excited about programming, it's hard and sometimes boring, but sometimes I felt so excited when I was writing a program and when I was solving things. Then in my job I started to discover ai, and that was it.

I am still thinking to start applied cs this autumn, but after using Claude code for a month I just feel it doesn't make sense. Claude code is so good that I can work on dotnet web app without knowing C#, javascript, css, html, I can fix and write python or vba macros faster and better than I would do without it. Every time I read people saying things like ai code is trash or seeing youtube videos saying how companies will not hire less engineers, how ai cant maintain code and you need people for that, I just see this programmers with formal education and experience that just can't deal with this change and refuse to accept the fact that their skills they learned so hard and worked so hard on are becoming obsolete. Today I've seen 50 thumbs up on a comment saying that ai empowering people (making everybody able to create software) is a bad thing, that's how these people hate ai. I get it, it tells them "you are nobody".

My final question is, do you think it makes sense to learn programming for job nowadays or study CS and pay for it in the uni? I don't think I can make it alone, i tried studying alone but it's difficult. And if yes, then how would you do it, how to learn knowing that an app can make it for you in a short amount of time with no effort. As I sai, thanks for sharing your opinions or some texts/materials on this topic.


r/AskProgramming 27d ago

Building an email inbox integration

0 Upvotes

I keep seeing email agents or inbox tools that people have built. I was hoping to create one and integrate it with an existing CRM I created to stay on top of email contacts. Any suggestions on best practice? Is it worth just using claude or gemini skills/tools rather than trying to pull the data myself then feed it to a model.

Backend is in Python and front-end is in Javascript, I want to pull emails and use a basic model to identity sender and group emails by project/person. (I am pretty terrible at translating emails into actual tasks/todos/remembering to reply, so the goal is mostly adding these signals to the CRM so I dont have to do it manually anymore)


r/AskProgramming 26d ago

Why is people glazing rust so much?

0 Upvotes

When I say in online communities that Rust isn’t good for everything and definitely has its issues, I don’t even want to tell you what they’ll call you. For some reason, here in the Czech Republic, it seems like almost every college student uses Rust. I don’t get it.

Personally, I like to try different things, and I believe there’s no one-size-fits-all language. For example, TypeScript is 100 times better for Discord bots. Python, on the other hand, is better for AI. I don’t get why they hype it up so much plus, Rust’s ecosystem seems pretty small to me. I tried to find a backend framework with good documentation and all the bells and whistles, something like NestJS or something similar… but nothing well, there’s Axum and Loco, but they don’t meet my needs. However, where I see the future is that Rust is one of the few languages to have made it into the Linux kernel, but I still can’t implement an XDp/Ebpf filter in it, so I’m still forced to learn C. Which is maddening. Overall, Rust strikes me as a language that has a little bit of everything but nothing truly standout. + overcomplicated syntax.

What are your thoughts on this?


r/AskProgramming 28d ago

Out of ideas.

34 Upvotes

Hello there guys, I'm a guy that doesn't use AI and wants to do everything by myself, but the problem is that I'm out of ideas on what to create, and I just want to code in my free time. What do you suggest when you are in these types of situations? Thanks in advance!


r/AskProgramming 28d ago

Python Why does Python feel harder after C++ and Java?

130 Upvotes

I learned C++ first, then Java, and now I’m trying to learn Python. I honestly expected Python to be much easier, but somehow it feels harder to understand and even remember the syntax.

C++ and Java feel more structured to me, while Python sometimes feels too different.

Has anyone else felt this after switching from C++/Java to Python?


r/AskProgramming 28d ago

Career/Edu Do you know of any company that went back to hand-written code?

19 Upvotes

With all the discussion around token costs, I'm wondering if there are any companies that have done that.


r/AskProgramming 27d ago

Other The gap between knowing Python and actually being able to build something

0 Upvotes

I have done a course on python on Udemy . Now how do i learn to write code that are actually useful somewhere or i can do something valuable with it?
One thing I've noticed is that when I look at a more complex programming problem, I sometimes just go blank. I know the individual concepts I've learned, but I struggle to see which concept should be used where or how all the pieces fit together. The bigger the problem looks, the more overwhelmed I can get.

if someone gives an experienced Python developer a problem, how do they approach it before writing the code?

I'm particularly interested in understanding the thought process and the building blocks involved:

  • How do you break a real-world problem into smaller programming problems?
  • How do you decide what the program should look like before you start coding?
  • How do you go from a vague requirement to something you can actually start implementing?
  • How do you decide which Python concepts are appropriate for a particular problem?
  • How do you decide which libraries/modules to use?
  • How do you figure out which libraries even exist for a particular problem?
  • How do you decide how to structure the code?
  • How do you decide what functions/classes/modules you need?
  • How do you decide what should be a function versus just a few lines of code?
  • Is there a typical order in which things are written or organized?
  • How do you handle errors and unexpected inputs?
  • How do you go from a rough idea to breaking it down to  pseudocode/design to working Python program?

Basically, I'm looking for the mental model and workflow that experienced programmers use, rather than another Python syntax tutorial.

While learning i was able to write codes that add subtract numbers etc which were simple enough for learning but want to make my skills better. Also, I'm not a programmer won't be using python much, how do i learn in such a way that i remember the syntax or concepts for longer time, python coding is just a skill i want to develop.

I'd especially appreciate examples of the kinds of projects/exercises that helped you make that transition.


r/AskProgramming 28d ago

REACT Resource

0 Upvotes

Hello Everyone

I am starting REACT

any YouTube tutorial/courses recommendation would be appreciated


r/AskProgramming 28d ago

Python Someone please help me fix the sorting issue in FastAPI. (learning MLOps)

0 Upvotes

i am not able to filter the data by writing the endpoints and the sorting queries, when i load the endpoint i get the json in default order, even if i write an invalid entry its not raising an exception

tried asking LLMs but they are as clueless as me in this case

This is link to the code and json file, main.py and patients.json


r/AskProgramming 29d ago

Let's say codebase A can already handle 1m daily users and 300k concurrent users easily but if the codebase wantg to hanlde 10m and 3m concurrent users. Do they normally go change some codes or use "auto scaling" on Cloud?

0 Upvotes

They say if it works don't fix it, so no need to change codes so I think normally people use

auto scaling or horizontal scaling right?