Thread: Concept On Stack

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    29

    Concept On Stack

    ***Background

    I understand that everything is added to the stack, when finished, removed from the stack.
    What I don't understand is the importance of programming to/around the stack.

    Here's how I view the stack:

    Linear:
    Create int, --> first process in stack.
    Add 5 to the int --> second process (becomes first when the creation finishes)

    Is that incorrect?

    Now, multi-threading:
    Begin main --> first process
    Begin function2 --> second process
    action in main --> third
    action in function2 --> fourth
    begin function 3 --> fifth
    action in main --> sixth
    action in function2 --> seventh
    action in function3 --> eighth

    Is that incorrect?
    As things finish they become higher up on the stack?

    ***What I Need This For

    Creating a server-client program. Information is passed from multiple clients to a server. The server then will update ALL the clients with information that is changed from the passed information in one client.

    Example:
    There are 5 clients, and 1 server.
    Client 1 sends an integer of 5.
    Client 3 sends an integer of 11.
    Server will perform action based on both sent integers, and then send information to Clients 1-5 about the upgrades.

    First, I may just be confusing multi-threading with stack. But if each thread contains it's own stack, then I don't understand how information communicates. But I believe I understand multi-threading, therefore the stack. If anyone can confirm - or unconfirmed the way it works, it'd be appreciated.
    I do like links, but I have already been doing a lot of exploring into the subject, some do not help -- as it is conceptual only. I do not need examples, I need explanations of what happens, why, and when. (Maybe not so much when, but things to note at least)

    Thank you for any help anyone can offer.

  2. #2
    Registered User
    Join Date
    Feb 2011
    Posts
    29
    Thread (computer science) - Wikipedia, the free encyclopedia
    Thread pool pattern - Wikipedia, the free encyclopedia

    I believe these articles have helped. But if anyone can offer further clarity, that would be awesome.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    That would work except for one thing... (In Windows at least) Each process has it's own separate stack and operates in it's own separate memory speace.

    A process stack operates as a first in - last out queue where things are pushed onto the stack and poped off in reverse order. In the case of CPU Registers this most often happens without the process knowing the address used. A register is PUSHED onto the stack then POPPED off later... it's like putting a sheets of paper on top of a pile... they come back off in the reverse order they went on... but you don't always know where any one sheet of paper is in the pile.

    Consider the extreme dificulty of making that work with 75 or 100 processes running on a typical computer.... Again the paper analogy... now you have 80 people tossing sheets of paper onto a single pile... you now have absolutely no way to know where that sheet of paper is and no way to get them back off the pile in any kind of reasonable order. So the only workable answer is to give every person their own separate pile... which they are required to keep track of on their own.

    What you are actually discussing is "interprocess communication" which is a whole lot more complex than just building a pile of papers...

    First the two communicating processes have to agree upon some means of passing data back and forth... this is usually a shared memory area but it can also be a network port, or even an external device such as a disk file.

    Interprocess Communications (Windows)

    Then comes the big problem. With several processes running asynchronously there is no guarantee that processes will complete in any known order. Your client might not finish before the server goes to get the data. So you need the means to make one process wait for another; a set of signals between processes saying "wait for me", "I'm done", "ok to go" etc.

    Synchronization (Windows)

    So, no, pushing an integer onto the stack of one process does not magically make it available to any other...

  4. #4
    Registered User
    Join Date
    Feb 2011
    Posts
    29
    Thanks CommonTater. That makes sense. Gonna look into the Synchronization aspect.
    What confuses me however, is that the process would happen based on received input. So, as it may be running a new thread (or... process/stack?) it would also be waiting for new information at the same time.
    Synching would be done once the first process is sent, and probably saved into a temporary file, so when it finishes the task it sends the information to everything that requests it, but it would have the responsibility to send it, not the process that created the thread. Also, the file would only update, so if the file isn't updated, if another thread asked for the information, it would use old information (as it should, because no new information is available)

    Does that make sense? Is that kinda what synchronization is? I'm trying to familiarize the process very linearly.

    In a Server - Multiple Client Approach
    1) Server Loops waiting for input
    2) Client sends information to server.
    3) Server opens up a new thread which will check the information, and then begin processing it.
    3.b) Client2 sends information to server.
    4) Server opens up new thread for Client2 "..."
    4.b) Client(1)'s information is processed, and stored to a temporary file. Then it begins sending the information to all Clients of the new information. Terminates new thread.
    5) Client2 checks information of temporary file, if needs to, reacts to it, if not, stores new information into the file -- replacing the old (if needed), and then sends all information to all clients, and also terminates thread.

    I'd believe, that would be synchronized, because the new thread/process itself would be ran and function off of globally saved accessible files.
    But.. I won't just guess, going to do some research on it, thanks for the info. Each stack is it's own pile.. need a way to share information.. humm..

    Again, thank you. I'll post my findings if I find some. I may even post a small program once I create it, that takes use of Multithreading, client-server, and possibly Hyper-threading. <-- But I have not yet done any research on the background of hyper-theading, and usability, or if it is possibly another name of multithreading.

    Thank you for the response, and your research that furthers my research. It really is beneficial.

  5. #5
    Registered User
    Join Date
    Feb 2011
    Posts
    29
    More links I've been reading:

    Multithreading Tutorial - CodeProject

    Part 1 & 2 (links provided in previous link also)
    http://www.ddj.com/windows/184402018...PCKHWATMY32JVN
    http://www.ddj.com/windows/184402029

    -----

    Maybe someone can answer this question:

    When creating threads, will the new thread use a different processor if available? -- or would you need to create a new process then have both processes interact?

    ------

    I haven't figured out my answer to the above.
    But for opening multiple threads in C code..

    Code:
    #include <stdio.h>
    #include <process.h>
    #include <windows.h>
    
    void thread(void *);
    
    int main(int argc, char *argv[]) {
        
        
        for(char x = 0; x!=10; x++) {
              _beginthread( thread, 0, (void*)x);
         }
        
        while(1) {
              printf("Main\n");
              //Sleep(1000);
         }
         
    }
    
    void thread(void *arg) {
         
         while(1) { 
              printf("Thread%d\n", (INT_PTR)arg);
              //Sleep(1000); 
         }
    }
    Opens up 10 threads other than main, and waits 1000 (miliseconds?), then reruns the thread.
    Kinda random which thread executes. I'm just learning, (obviously). This is if anyone else wishes to learn from my thread.
    Last edited by Crosility; 02-26-2011 at 03:17 AM.

  6. #6
    Registered User
    Join Date
    Feb 2011
    Posts
    29
    I've actually come across an issue, if anyone can help.

    Code:
    #include <stdio.h>
    #include <process.h>
    #include <windows.h>
    #include <time.h>
    
    void thread(void *);
    
    int main(int argc, char *argv[]) {
         
         getchar();
         
         double totaltime = clock();
         int totaltime2 = time(0);
         
        for(int x = 0; x!=2000; x++) {
              _beginthread( thread, 0, (void*)x);
              Sleep(9);
         }
             
        while(1) {
              puts("Main Thread is Sleeping");
              printf("Total Time: %.2f\n", (clock()-totaltime)/1000);
              printf("Total Time2: %d\n", time(0)-totaltime2);
              Sleep(30000);
         }
    
    }
    
    void thread(void *arg) {
         
         Sleep((INT_PTR)arg * 9);
         printf("Thread%d created.\n", (INT_PTR)arg);
         
         /*
         double total = clock();
         
         for (int x = 0; x<=10; x++) { 
              printf("Thread%d = %d\n", (INT_PTR)arg, x);
         }
         
         total = clock() - total;
         
         printf("Thread%d is finished, and now sleeping\n");
         Sleep(120000);
         printf("Thread%d finished in %.2f seconds\n", (INT_PTR)arg, total/1000 );
         */
         
         Sleep(60000);
         printf("Thread%d is being destroyed.\n", (INT_PTR)arg);
    }
    ***The Problem:

    My limit is 891 threads. I need to be able to create more. I'm doing research to find out how to change this. With no luck. My console gives me the message of only 889 created, and thread 889 destroyed.
    My Resource Monitor shows 891. :|

    I am using my favorite compiler: BloodShed Dev-C++.. I'll probably upgrade to V.5 beta later. Maybe that'll change it. But any other ideas on the problem would be great!

    ----------------

    ***Answer::

    Found answer.
    It assigns itself a set amount of space. Once that space is filled, it cannot give anymore set addresses. Therefore will fail in creating more threads. It's interesting, and I need to find a way to...

    ***New Problem:
    Change the size of the allocated space when creating the new thread.
    Some threads need lots of space, while others.. very very very little space. Like, 50 bytes MAX. Those threads would be for calculating time.. only. When the time is up, sending a signal somewhere. But nothing else.
    Now.. where can I find a way to change the space upon creation? --- humm..
    Keep reading I suppose.

    ***Not the answer..

    _beginthread( thread, 0, (void*)x);

    thread -- function to start thread with. (Not sure how to pass additional parameters?)

    0, -- Size of thread stack (in bytes according to:
    http://msdn.microsoft.com/en-us/libr...=vs.85%29.aspx
    Tried changing it to 10, and 20. No difference to max threads.

    (void*)x -- Thread number (like a reference). Important if you use different numbers for each thread. I used it in terms of a loop. So.. yea.
    Last edited by Crosility; 02-26-2011 at 03:15 PM.

  7. #7
    'Allo, 'Allo, Allo
    Join Date
    Apr 2008
    Posts
    639
    Quote Originally Posted by Crosility View Post
    My limit is 891 threads. I need to be able to create more.
    I have a hard time believing that someone who didn't know what multithreading was two days ago ago now requires more of them than the whole of Windows 7, 4 Internet Explorer 8 tabs, 2 copies of Visual Studio and a Firefox tab put together.

    What you need is a different approach:
    Quote Originally Posted by Gamedev Network Forum FAQ
    Q10) Should I spawn a thread per connection in my game code?
    A10) The short answer is "likely no." The longer answer is that, if you're using UDP, you should only need a single socket, from which you can read a packet, process a packet, repeat. If you're using TCP, you will need a socket per player, but the players are likely sharing and affecting a single world state inside the program, which needs to be protected by locking; thus, the extra threads would just end up blocking on locks anyway, so using select() and reading out what's there, then processing it, is recommended. Some users find "co-operative threads" or fibers to be a nice middle ground, because it gives some of the advantages of real threads (a stack per context) without the locking overhead (because yield is explicit).
    That mentions games, but the advice is general. Here's the rest of it, it might be helpful.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Yeah, I have to agree with adeyblue on this one.

    Debugging a simple sequential program has a difficultly in the range of 1 to 10.

    Debugging a thread fiasco pushes that up to like 1000. Threads seem all nice and dandy when you only have a handful. But get a few more, and Race conditions start appearing. The problem is, ANYTHING you do to the code to try and investigate them makes the problem go away. These are called Heisenbug's. Until you've chased one, you've no idea how annoying they can be.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Registered User
    Join Date
    Feb 2011
    Posts
    29
    Quote Originally Posted by adeyblue View Post
    Windows 7, 4 Internet Explorer 8 tabs, 2 copies of Visual Studio and a Firefox tab put together.

    What you need is a different approach:
    2 days ago I knew my goal. It has not changed.
    The thing about all those things running mentioned: They are either to maintain visual, background, or awaiting input to begin a new thread.

    I was looking into more threads for use inside of a server.

    I agree, I'm looking at different approaches, but I'm sure you would agree. You look at all approaches (or as many different ones as possible) before sticking to one. 2 days ago I had no idea how to program to do multithreading, I -- kinda -- understood it. I understand it much more now. Much more needed to be able to see if it's a reasonable approach.

    I'll look into other ways. Thank you for the new links. After I'm fully awake, I'll look into them.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stack and pointer problem
    By ramaadhitia in forum C Programming
    Replies: 2
    Last Post: 09-11-2006, 11:41 PM
  2. infix evaluation using stack
    By lewissi in forum C++ Programming
    Replies: 0
    Last Post: 11-03-2005, 02:56 AM
  3. Question about a stack using array of pointers
    By Ricochet in forum C++ Programming
    Replies: 6
    Last Post: 11-17-2003, 10:12 PM
  4. error trying to compile stack program
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-03-2003, 06:27 PM
  5. Stack Program Here
    By Troll_King in forum C Programming
    Replies: 7
    Last Post: 10-15-2001, 05:36 PM

Tags for this Thread