Menu
  • HOME
  • TAGS

RobotC: Multithreading in TeleOp (controlling mode)

Tag: multithreading,robot

I am making a program for a robot in a competition, and need to multithread.

When I make a second task (task two()) and try to start (startTask) it with a button press from a controller, it just executes the first statement of the task and only as long as the button is pressed, instead of the whole block. I've tried many things including putting a loop in the second task also, using a function instead of a task and sleeping for 200 milliseconds before, and after the startTask(two); function, but the same thing happens every time.

I can't post my program because I don't want other people to steal it, sorry.

What edits will make it run the whole block? Any help would be appreciated.

Best How To :

Since this is Controller Mode, I'm assuming that you are setting the motors to stop when the corresponding button is not pressed.

if([...])
[...]
else
{
   setMotorSpeed(motor10, 0);
}

This is the cause for the stopping of the motors when you release. All of the other methods that you tried had nothing to do with this, so they shouldn't have worked.

You need to put something like this:

int  Motor10Speed;
[...]
if([...])
[...]
else
{
   setMotorSpeed(motor10, Motor10Speed);
}

This will control an individual motor. Repeat this for all other motors being used.

After that is done, make the function look something like this:

task mini_function();

task main()
{
[...]
}

task mini_function()
{
Motor10Speed = 50;
sleep(1000);
Motor10Speed = 0;
}

Expand the above program so it matches your current function, while using the MotorSpeed variables as setMotorSpeed variables.

This should make you able to drive and run a function at the same time without them interrupting each other.

EntityFramework 6 / SqlCe 4 SaveChangesAsync()

c#,wpf,multithreading,entity-framework,sqlce

After some more testing it appears that I shouldn't be using the await keyword in he call to the async method. Executing the call like this: Task.Run(() => PerformContextSubmitAsync()); Doesn't block the original calling thread, but it doesn't seem to actually execute in an asynchronous fashion. It seem to behave...

Looking to pause a thread using thread.sleep

java,multithreading

You're probably running into a race condition between the two threads, the fact that i isn't volatile also suggests that the threads may not be working with the same actual value as each other. Threads are also non-reentrant, meaning that once the run method exists, they can not be restarted....

Interaction with user on Thread cause my app crash [duplicate]

android,multithreading,java-threads

This should do the trick: private class StreamThread extends Thread { public StreamThread() {} public void run() { byte[] buffer = new byte[1024]; int bytes; while (true) { try { bytes = mmInStream.read(buffer); String message = new String(buffer, 0, bytes); runOnUiThread(new Runnable() { @Override public void run() { ((TextView) findViewById(R.id.textView)).setText(message);...

c - Parallelising a function

c,multithreading,table,rainbowtable

The best way to parallelize the above function without facing concurrency issues is to create as many memory streams as many threads you wish to use and then divide the task into fractions, like if you have 4 threads, one thread performs the task from 0 to mMax / 4...

Is there standard implementation for thread block/resume in java SE?

java,multithreading,wait

have a a look at the classes in java.util.conucurrent ... CountDownLatch might be a solution for your problem if i understand your problem correctly.

Show imageview after click wait a moment then hide again [Android]

android,multithreading,imageview,show-hide

imageView.setVisibility(View.VISIBLE); new Handler().postDelayed(new Runnable() { @Override public void run() { imageView.setVisibility(View.INVISIBLE); } }, ms); ms is time duration in milliseconds....

How can I know the lock information in java?

java,multithreading,locking

You can use ThreadInfo#getLockedSynchronizers() (JavaDoc) via ThreadMXBean to get array of LockInfo on currently owned locks on threads. LockInfo will tell you just class name & identity hashcode of a lock, but that's sufficient in tracing lock objects.

Atomic/not-atomic mix, any guarantees?

c++,multithreading,c++11,atomic

As long as your used memory order is at least acquire/release (which is the default), you are guaranteed to see all updates (not just the ones to atomic variables) the writing thread did before setting the flag to true as soon as you can read the write. So yes, this...

Pthread id and sleep

c,multithreading,pthreads

Your argument passing is fine. But you are not passing the value to sleep. It should be sleep(*p); p points the address of i (from the function th()). You need to dereference the pointer to get the value....

How to calculate how many times each thread executed a critical section in OpenMP?

c,multithreading,openmp

Create an array large enough to store the values for all your threads and increment them in your code: unsigned int count[PID_MAX_LIMIT]; // global and/or static memset(count, 0, sizeof(int) * sizeof(count)) for(i = 1; i < SIZE; i++) { ... count[get_tid()]++; } Then, you just have to display the non-zero...

C# Threading : Threads executed on incorrect object

c#,multithreading

That's because you're using the same shared instance of record for all your threads. An easy way to fix the issue is to use a parameter when starting your thread: internal void Start(QMail rec) { Thread thread = new Thread(new ParameterizedThreadStart(ProcessThread)); thread.IsBackground = true; thread.Start(rec); } Then, in the thread,...

Why does this code catch block not execute?

c++,multithreading,error-handling,try-catch

You forgot to join the thread : try { thread t(do_work); t.join(); // <<< add this std::cerr << "THROWING" << std::endl; throw logic_error("something went wrong"); } catch (logic_error e) { std::cerr << "GOTCHA" << std::endl; } A joinable thread that goes out of scope, causes terminate to be called. So,...

How can we make a thread to sleep for a infinite time in java?

java,multithreading,thread-sleep

Probably Thread.sleep(Long.MAX_VALUE) is enough, but if you want to make sure: while (true) { Thread.sleep(Long.MAX_VALUE); } ...

wait for an event regulary

multithreading,events

I solve it I use threading and producer/consumer problem. after an event it will wait until event method run.

How does the kernel separate threads from processes

linux,multithreading,linux-kernel

Unlike Windows, Linux does not have an implementation of "threads" in the kernel. The kernel gives us what are sometimes called "lightweight processes", which are a generalization of the concepts of "processes" and "threads", and can be used to implement either. It may be confusing when you read kernel code...

hashmap iterator when used inside synchronized method

java,multithreading,hashmap

Calling iterator() creates a new Iterator positionned at the begin of the collection, so it will always give you the first entry of you Map implementation. When using HashMap, ordering is undefined, but you can use other Map implementations to control the ordering (LinkedHashMap, TreeMap, ...)...

Calling dispatch_sync from a concurrent queue - does it block entirely?

ios,objective-c,multithreading,swift,grand-central-dispatch

dispatch_sync will block the caller thread until execution completes, a concurrent queue has multiple threads so it will only block one of those on that queue, the other threads will still execute. Here is what Apple says about this: Submits a block to a dispatch queue for synchronous execution. Unlike...

Interleaving processes on two threads

c#,multithreading,synchronization

If I am understanding the pseudocode correctly, you want to trigger off the fetch operation on a background thread and yield the results with an iterator as they come in, rather than waiting for the entire fetch operation to complete before returning. A couple of things that I would change:...

Set Label From Thread

vb.net,multithreading,winforms

The reason is that you are referring to the default instance in your second code snippet. Default instances are thread-specific so that second code snippet will create a new instance of the Form1 type rather then use the existing instance. Your Class1 needs a reference to the original instance of...

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread

c++,multithreading,sorting,recursion

You problem originates in this line: int newArray[maxCount + 1]; You are trying to allocate ~250000 ints on the stack (on most 32 bit platforms it will take ~1MB of memory). Your thread's stack may not be able to do this. By the way, you should not do this -...

Sequential file IO from different threads fail with FileSystemException

java,multithreading,windows-7,io

You simply had some typo in your FileMover run method: Path destination = origin.resolve(origin.getFileName().toString().replace(".in", ".out")); The destination will be like C:\temp\file_0.in\file_0.out this won't work, because it is a file and not a directory :-) Replace it something like that: String now = origin.toString().replace(".in", ".out"); Path destination = Paths.get(now); ...

Node.js and C/C++ integration: how to properly implement callbacks?

c++,node.js,multithreading

Calling callback from a different thread is not an options, v8 doesn't allow that. So you have to go with b. It's not so hard to implement actually. I recommend to use nan for this task. Here is an example from docs: class PiWorker : public NanAsyncWorker { public: PiWorker(NanCallback...

Simple thread/mutex test application is crashing

c++,multithreading,c++11,mutex,mingw-w64

workers.clear(); is not going to join all of the threads. Calling clear() will call the threads' deconstructors. std::thread::~thread will call std::terminate() if the thread is joinable(). Since you are calling clear() on the vector right after you create the vector the threads are still processing and are joinable. You have...

Calling Python code from Twisted

python,multithreading,twisted

At first reading, I though you were implying twisted isn't python. If you are thinking that, keep in mind the following: Twisted is a python framework, I.E. it is python. Specifically it's about getting the most out of a single process/thread/core by allowing the programmer to hand-tune the scheduling/order-of-ops in...

How to test running threads if they are terminating properly when they all done using JUnit

java,multithreading,junit

You can use an ExecutorService with a predefined number of threads and submit your jobs to this ExecutorService. When that is done you can attempt to shut down the executor (no jobs will be halted by this operation). Then you can poll the executor to see whether all jobs are...

Exclusive lock using key in .NET

c#,.net,multithreading,locking

Put lock objects into dictionary indexed by the key - Dictionary<string, object> and grab objects by key to lock. If you need to dynamically add new key/lock object pairs make sure to lock around the dictionary access, otherwise if after construction you only read values from dictionary no additional locking...

Any way to catch an exception occurring on a thread I don't own?

c#,multithreading,exception

The thing worrying me most in the described case is abnormal thread termination inside that 3rd-party lib. Once a thread is throwing, you can't catch the exception via correct way because you're not the owner of that thread invocation (and it has no idea it should propagate the exception to...

Difference between thread.join and thread.abort in python multithreading

python,multithreading

.join() and setting a abort flags are two different steps in cleanly shutting down a thread. join() just waits for a thread that is going to terminate anyway to be finished. Thus: import threading import time def thread_main(): time.sleep(10) t = threading.Thread(target=thread_main) t.start() t.join() This is a reasonable program. The...

Run class methods in different threads

java,multithreading,object,methods

public class HelloRunnable implements Runnable { private MyClass myClass; private boolean execMethod1; private boolean execMethod2; private boolean execMethod3; public HelloRunnable(MyClass myClass, boolean execMethod1, boolean execMethod2, boolean execMethod3) { this.myClass = myClass; this.execMethod1 = execMethod1; this.execMethod2 = execMethod2; this.execMethod3 = execMethod3; } public void run() { if(execMethod1) myClass.method1(); else if(execMethod2) myClass.method2();...

Multi-Threading error when binding a StringProperty

java,multithreading,javafx,javafx-8

It is wrong to call code that results in changes to the UI from a thread other than the FX Application Thread, regardless of whether or not it throws an exception. The FX toolkit makes a best effort to throw an exception if you violate this rule, but in some...

std::condition_variable – notify once but wait thread wakened twice

c++,multithreading

Converting comments into answer: condition_variable::wait(lock, pred) is equivalent to while(!pred()) wait(lock);. If pred() returns true then no wait actually takes place and the call returns immediately. Your first wake is from the notify_one() call; the second "wake" is because the second wait() call happens to execute after the Stop() call,...

What happens if all node.js's worker threads are busy

javascript,node.js,multithreading

I/O in general does not block the event loop (there are some exceptions like the crypto module currently and things like fs.*Sync() methods) and especially in the case of network I/O, the libuv thread pool is not used at all (only for things like dns (currently) and fs operations). If...

C++ Ubuntu select() if serial interface has data on asynchronous read

c++,multithreading,ubuntu,asynchronous,serial-port

Didn't specify a fd_set to read. Try this: fd_set readfs; /* file descriptor set */ FD_ZERO(&readfs); /* clear the set */ FD_SET(fd, &readfs); /* put the fd in the set */ int ret = select(fd + 1, &readfs, 0, 0, &tv); Edit: That should also solve your other question. Each...

Crystal convert the idea behind Thread pool to Fibers/spawn

multithreading,coroutine,crystal-lang

Something like this: require "socket" ch = Channel(TCPSocket).new 10.times do spawn do loop do socket = ch.receive socket.puts "Hi!" socket.close end end end server = TCPServer.new(1234) loop do socket = server.accept ch.send socket end This code will pre-spawn 10 fibers to attend the requests. The channel is unbuffered so the...

performance issues executing list of stored procedures

c#,multithreading,performance,loops

What I would do is something like this: int openThread = 0; ConcurrentQueue<Type> queue = new ConcurrentQueue<Type>(); foreach (var sp in lstSps) { Thread worker = new Thread(() => { Interlocked.Increment(ref openThread); if(sp.TimeToRun() && sp.HasResult) { queue.add(sp); } Interlocked.Decrement(ref openThread); }) {Priority = ThreadPriority.AboveNormal, IsBackground = false}; worker.Start(); } //...

Web API - Set each thread with the HttpRequestMessage id?

c#,.net,multithreading,task-parallel-library,web-api

For context related problems, you can use CallContext.LogicalSetData and CallContext.LogicalGetData, which is merely an IDictionary<string, object> which flows between contexts, and has a copy-on-write (shallow copy) semantics. Since your data is immutable (according to the docs), you can map your correlation id to your threads managed thread id: protected async...

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?

ios,objective-c,multithreading,swift,grand-central-dispatch

This will not deadlock since the dispatched block can start running immediately - it's not a serial queue so it doesn't have to wait for the current block to finish. But it's still not a good idea. This will block one thread causing the OS to spin up a new...

Thread synchronisation for C++ map

c++,multithreading,dictionary,pthreads

I understand that reading using the [] operator, or even modifying the elements with it is thread safe, but the rest of the operations are not. Do I understand this correctly? Well, what you've said isn't quite true. Concurrent readers can use [] to access existing elements, or use...

Opening facebook in a panel of winforms

c#,multithreading,facebook,panel,process.start

try this Process.Start("http://www.google.com"); or If the point is to open a website in your application, you will have to use WebBrowser control. Put WebBrowser control on your form, and add this code to the button which is responsible for opening the site: webBrowser1.Navigate("www.google.com");...

Does wait() need synchronization on local variable

java,multithreading,synchronization

I don't know Android development tools, but the warning sounds over-zealous. The compiler is trying to help you to avoid synchronizing on an instance that is only visible to a single thread. It's smart enough to know that the local variable, r, can only be seen by one thread, but...

Invoke form showdialog is not modal

vb.net,multithreading,invoke

in the showDialog, you can set the parent form which causes the child to become modal: Public Class MainForm Dim frm2 As Form2 Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load frm2 = New Form2() Dim frmHandle As IntPtr = frm2.Handle frm2.Button1.Text = "test" System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf DoSomething), 0)...

Visualvm thread started count

java,multithreading,profiling,visualvm

Make sure that your program is using ThreadPool, which will make efficient use of threads. The total thread count is number of threads started since the JVM is started. Live threads started(peak) is 126 threads so this looks normal & current live thread count is 112 this include all the...

How do you start a function at a certain time in Python?

python,multithreading,events,time,condition

There are several ways -- some are more easily portable to different operating systems than others. Generally, what you could do is: spawn a new thread for every task in each thread, get the current time, and time.sleep() for the remaining time That works, but it's not extremely accurate. You...

Recognizing Blocked Swing EDT

java,multithreading,swing

Apart from being blocked by Thread.sleep(), the EDT could e.g. be blocked when waiting for an asynchronous operation. Here's an example that -- after the "Click & Wait" button is pressed -- blocks the EDT until the main thread can read text from the console. You will notice that the...

Multiple Threads searching on same folder at same time

c#,multithreading,file-search

Instead of using ordinary foreach statement in doing your search, you should use parallel linq. Parallel linq combines the simplicity and readability of LINQ syntax with the power of parallel programming. Just like code that targets the Task Parallel Library. This will shield you from low level thread manipulation and...

Images not appearing on WPF form when loading asynchronously

c#,wpf,multithreading,listbox,backgroundworker

@Clemens answer from his comment on the original question provided the solution. Ensuring that the file stream was being closed responsibly and changing the BitmapCacheOption to OnLoad now shows each image in the asynchronous load. The final code for the asynchronous load looks like: private void LoadAsync(object sender, DoWorkEventArgs e)...

Java how to limit number of threads acting on method

java,multithreading,memory-management

You can use the Executor.newFixedThreadPool idiom, internally to your execution logic. Full example below: public class Main { public static void main(String[] args) throws Exception { Main m = new Main(); // simulating a window of time where your method is invoked continuously for (int i = 0; i <...

Java 5 Multi threading, catch thread exceptions

java,multithreading,exception,concurrency,java-5

The most common approach is to submit a Callable to an Executor, and receive a Future. You can then call Future.get to find out if any exceptions were thrown. As for UncaughtExceptionHandler, you can only really use it with raw threads because Executors handle uncaught exceptions internally (thus you don't...

Guarantee TransformBlock output sequence

c#,multithreading,async-await,task-parallel-library,tpl-dataflow

TransformBlock already maintains FIFO order. The order in which you post items to the block is the exact order in which the items will be returned from the block. When you specify a maximum degree of parallelism that is larger than 1, multiple messages are processed simultaneously, and therefore, messages...

java multithreading start() and run() [duplicate]

java,multithreading

We cannot predicate output order in case of Threads. Multithreading t1 = new Multithreading(); Multithreading t2 = new Multithreading(); t1.start(); // Thread is executing your run() method t2.run(); // It is a normal execution of run() method. No Thread is here ...