I am trying to build a simple "scheduler" in an asynchronous context. Here is a piece of the some sample code that will not compile because the Future is "not sync". What I don't understand is...why is it not sync? I am using an Arc<RwLock> for the data structures that I'm using. I can't even access them without locking, so why am I not Sync?
Here is the example code:
async fn testing_theory(mut thing: JobScheduler) -> Result<(), JobError>
{
let other_job = Job::new_one_shot(Duration::from_secs(20), |_uuid, _l| Box::pin(async move { println!("Extra"); Ok(()) }))?;
thing.add(other_job).await.unwrap();
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
let mut sched = JobScheduler::create();
let four_s_job_async = Job::new_cron_job("1/4 * * * * *", |_uuid, l| Box::pin(async move {
println!("{:?} I am a cron job run async every 4 seconds", chrono::Utc::now());
let job_catch = l.clone();
testing_theory(job_catch).await;
Ok(())
}))?;
let four_s_job_guid = four_s_job_async.get_job_id().await;
sched.add(four_s_job_async).await.unwrap();
And here is the error I'm getting:
error: future cannot be shared between threads safely
--> examples/simple_job.rs:15:74
|
15 | let four_s_job_async = Job::new_cron_job("1/4 * * * * *", |_uuid, l| Box::pin(async move {
| ____________________________________________________________________^
16 | | println!("{:?} I am a cron job run async every 4 seconds", chrono::Utc::now());
17 | | let job_catch = l.clone();
18 | | testing_theory(job_catch).await;
19 | | Ok(())
20 | | }))?;
| |^ future created by async block is not Sync
|
= help: the trait Sync
is not implemented for dyn Future<Output = Result<(), JobError>> + Send
note: future is not Sync
as it awaits another future which is not Sync
--> examples/simple_job.rs:7:5
|
7 | thing.add(other_job).await.unwrap();
| ^^^^^^^^^^^^^^^^^^^^ await occurs here on type Pin<Box<dyn Future<Output = Result<(), JobError>> + Send>>
, which is not Sync
= note: required for the cast to the object type dyn Future<Output = Result<(), JobError>> + Send + Sync
If someone can help me with the error, I'd appreciate it, but I'm mostly interested in...how do I debug this? How do I figure out what variable or situation is causing the Sync error?
Thank you